There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y).

We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi).

Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid.

Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves.

Input & Output

Example 1 — No Blocked Cells
$ Input: blocked = [], source = [0,0], target = [999999,999999]
Output: true
💡 Note: With no blocked cells, we can always reach any cell from any other cell in the grid.
Example 2 — Source is Enclosed
$ Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
Output: false
💡 Note: The source [0,0] is blocked by cells [0,1] and [1,0], forming a corner trap that prevents reaching [0,2].
Example 3 — Path Exists Around Blocks
$ Input: blocked = [[0,1]], source = [0,0], target = [0,2]
Output: true
💡 Note: Even with [0,1] blocked, we can go from [0,0] → [1,0] → [1,1] → [1,2] → [0,2] to reach the target.

Constraints

  • 0 ≤ blocked.length ≤ 200
  • blocked[i].length == 2
  • 0 ≤ xi, yi < 106
  • source.length == target.length == 2
  • 0 ≤ sx, sy, tx, ty < 106
  • source ≠ target
  • It is guaranteed that source and target are not blocked.

Visualization

Tap to expand
Problem: Escape a Large Maze1M × 1M GridSTXXXSource: Starting positionTarget: Goal to reachAlgorithm:1. Use BFS from source2. Count explored cells3. If count > B*(B-1)/2: Not trapped!4. Repeat from target5. Path exists if both free
Understanding the Visualization
1
Input
Grid with source, target, and blocked cells
2
Process
Check if path exists using BFS with area limits
3
Output
Return true if path exists, false if blocked
Key Takeaway
🎯 Key Insight: Any enclosure formed by B blocked cells has maximum area B*(B-1)/2, allowing efficient detection of trapped positions
Asked in
Google 15 Amazon 8
18.5K Views
Medium Frequency
~35 min Avg. Time
432 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