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: true
💡 Note: Player needs 2 steps to reach [2,0], ghost needs 1 step. Player can reach target before ghost intercepts.
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: Can Player Reach Target First?PACPlayer [0,0]👻Ghost [1,0]👻Ghost [0,2]🎯Target [3,1]Player: 4 stepsGhost1: 3 stepsResult: FALSEGhost can reach target faster than playerManhattan Distance: |x1-x2| + |y1-y2|
Understanding the Visualization
1
Initial Setup
Player at [0,0], ghosts at various positions, target location
2
Distance Analysis
Calculate Manhattan distances for optimal paths
3
Escape Decision
Return true only if player is fastest to target
Key Takeaway
🎯 Key Insight: Use Manhattan distance to determine if any ghost can intercept the player's path to the target
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