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
Escape a Large Maze INPUT 1M x 1M Grid S(0,0) T(999999,999999) blocked = [] source = [0, 0] target = [999999, 999999] blocked.length <= 200 Max blocked area limited to ~19900 cells ALGORITHM STEPS 1 Limited BFS Run BFS from source with visit limit 2 Check Escape If visited > 19900 or reached target: not trapped 3 Reverse BFS Run BFS from target with same limit 4 Return Result Both not trapped means path exists BFS Queue [0,0] [0,1] [1,0] Directions: N,E,S,W FINAL RESULT S T No blocked cells Path is clear! true Source can reach Target through valid moves OK - Reachable Key Insight: With at most 200 blocked cells, the maximum area that can be enclosed is ~19,900 cells (using blocked cells against a corner). If BFS visits more cells than this limit without being trapped, the source/target cannot be enclosed. Check both directions to confirm path exists. TutorialsPoint - Escape a Large Maze | BFS Approach
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