Escape The Ghosts - Problem

You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [x_target, y_target] that you are trying to reach.

There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [x_i, y_i] represents the starting position of the i-th ghost.

Each turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions (north, east, south, west), or stay still. All actions happen simultaneously.

You escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.

Return true if it is possible to escape regardless of how the ghosts move, otherwise return false.

Input & Output

Example 1 — Ghost Blocks Escape
$ Input: ghosts = [[1,0]], target = [1,0]
Output: false
💡 Note: Player needs 1 step to reach [1,0], but ghost is already there (0 steps). Ghost reaches target before player.
Example 2 — Successful Escape
$ Input: ghosts = [[1,0]], target = [2,0]
Output: false
💡 Note: Player needs 2 steps to reach [2,0], ghost needs 1 step. Ghost can reach target before player.
Example 3 — Multiple Ghosts
$ Input: ghosts = [[2,0],[1,1]], target = [1,0]
Output: false
💡 Note: Player needs 1 step. First ghost needs 1 step, second ghost needs 1 step. Ghost reaches target at same time, blocking escape.

Constraints

  • 1 ≤ ghosts.length ≤ 100
  • ghosts[i].length == 2
  • -1000 ≤ xi, yi ≤ 1000
  • -1000 ≤ xtarget, ytarget ≤ 1000

Visualization

Tap to expand
Escape The Ghosts - Optimal Solution INPUT YOU [0,0] GHOST TARGET ghosts = [[1, 0]] target = [1, 0] Ghost IS at target! Player Ghost Target ALGORITHM STEPS 1 Calculate Your Distance Manhattan: |0-1| + |0-0| = 1 2 Calculate Ghost Distance Ghost[0]: |1-1| + |0-0| = 0 3 Compare Distances Your dist (1) vs Ghost (0) 4 Decision Logic Ghost can reach first! Entity Distance You 1 Ghost 0 (already there!) FINAL RESULT Ghost at Target false Cannot Escape Ghost already at target You cannot escape! Key Insight: Use Manhattan distance to compare who reaches target first. You can only escape if YOUR distance to target is STRICTLY LESS than ALL ghosts' distances. Equal distance means ghost catches you! Formula: Manhattan Distance = |x1 - x2| + |y1 - y2| | Time: O(n) | Space: O(1) TutorialsPoint - Escape The Ghosts | Optimal Solution (Manhattan Distance)
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
945 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen