Skip to content

1036. Escape a Large Maze

Description

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.

 

Example 1:

Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
Output: false
Explanation: The target square is inaccessible starting from the source square because we cannot move.
We cannot move north or east because those squares are blocked.
We cannot move south or west because we cannot go outside of the grid.

Example 2:

Input: blocked = [], source = [0,0], target = [999999,999999]
Output: true
Explanation: Because there are no blocked cells, it is possible to reach the target square.

 

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.

 

Solutions

Solution: Depth-First Search

  • Time complexity: O(blocked.length2)
  • Space complexity: O(blocked.length2)

 

JavaScript

js
/**
 * @param {number[][]} blocked
 * @param {number[]} source
 * @param {number[]} target
 * @return {boolean}
 */
const isEscapePossible = function (blocked, source, target) {
  if (!blocked.length) return true;
  const n = 10 ** 6;
  const maxBlockedArea = blocked.length ** 2 / 2;
  const blockedSet = new Set();

  for (const [x, y] of blocked) {
    blockedSet.add(x * n + y);
  }

  const escapeMaze = ([x, y], seen, exit) => {
    if (x < 0 || y < 0 || x >= n || y >= n) return false;
    if (seen.size > maxBlockedArea) return true;
    if (exit[0] === x && exit[1] === y) return true;
    const key = x * n + y;

    if (blockedSet.has(key) || seen.has(key)) return false;
    seen.add(key);

    const right = escapeMaze([x + 1, y], seen, exit);
    const left = escapeMaze([x - 1, y], seen, exit);
    const lower = escapeMaze([x, y + 1], seen, exit);
    const upper = escapeMaze([x, y - 1], seen, exit);

    return right || left || lower || upper;
  };

  return escapeMaze(source, new Set(), target) && escapeMaze(target, new Set(), source);
};

Released under the MIT license