LeetCode 789: Escape The Ghosts Solution
Master LeetCode problem 789 (Escape The Ghosts), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To determine if it is possible to escape the ghosts and reach the target before any ghost catches up, we need to calculate the Manhattan distance between the player's current position and the target, as well as the Manhattan distance between each ghost's position and the target. If the player's distance to the target is less than the distance of any ghost to the target, then the player can escape.
Algorithm
- Calculate the player's Manhattan distance to the target.
- For each ghost, calculate the Manhattan distance to the target.
- If the player's distance is less than or equal to any ghost's distance, return false.
- If the player's distance is greater than all ghosts' distances, return true.
Time Complexity
The time complexity of this algorithm is O(n), where n is the number of ghosts.
Space Complexity
The space complexity of this algorithm is O(1), as we are not using any extra space other than a few variables.
Solution Code
class Solution {
public boolean escapeGhosts(int[][] ghosts, int[] target) {
int playerDist = Math.abs(target[0]) + Math.abs(target[1]);
for (int[] ghost : ghosts) {
int ghostDist = Math.abs(ghost[0] - target[0]) + Math.abs(ghost[1] - target[1]);
if (ghostDist <= playerDist) {
return false;
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 789 (Escape The Ghosts)?
This page provides optimized solutions for LeetCode problem 789 (Escape The Ghosts) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 789 (Escape The Ghosts)?
The time complexity for LeetCode 789 (Escape The Ghosts) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 789 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 789 in Java, C++, or Python.