Sponsored
Sponsored
This approach calculates the Manhattan distance from the starting point (0,0) to the target for you, and for each ghost from their starting position to the target. You can only escape if your distance to the target is strictly less than every ghost's distance to the target, meaning you reach the destination before any ghost can get there.
Time Complexity: O(n), where n is the number of ghosts. Space Complexity: O(1).
1class Solution {
2 public boolean escapeGhosts(int[][] ghosts, int[] target) {
3 int playerDist = Math.abs(target[0]) + Math.abs(target[1]);
4 for (int[] ghost : ghosts) {
5 int ghostDist = Math.abs(ghost[0] - target[0]) + Math.abs(ghost[1] - target[1]);
6 if (ghostDist <= playerDist) {
7 return false;
8 }
9 }
10 return true;
11 }
12}
This Java code uses Manhattan distance calculations. It returns false if any ghost can reach the target as fast or faster than the player.
This approach involves simulating every possible move for you and each ghost simultaneously. For each time step, move each entity towards the target or keep them in the same position if they're already there. This approach is generally inefficient but illustrates the problem space.
Time Complexity: O(n), where n is the number of ghosts. Space Complexity: O(1).
1var
The JavaScript implementation uses distance checks, reflecting the impracticality of simulating every move exactly.