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).
1var escapeGhosts = function(ghosts, target) {
2 const playerDist = Math.abs(target[0]) + Math.abs(target[1]);
3 for (let ghost of ghosts) {
4 const ghostDist = Math.abs(ghost[0] - target[0]) + Math.abs(ghost[1] - target[1]);
5 if (ghostDist <= playerDist) {
6 return false;
7 }
8 }
9 return true;
10};
This JavaScript function determines if the player can reach the target before any ghost by comparing the respective Manhattan 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.