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).
1public class Solution {
2 public bool EscapeGhosts(int[][] ghosts, int[] target) {
3 int playerDist = Math.Abs(target[0]) + Math.Abs(target[1]);
4 foreach (int[] ghost in 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 C# code calculates the player's and each ghost's distance to the target and checks if the player can escape based on these distances.
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).
1#
While this C implementation can theoretically simulate each move, it is essentially a version of the Manhattan Distance Comparison approach, as full simulation is infeasible for large inputs.