|
| 1 | +/** |
| 2 | + * 1036. Escape a Large Maze |
| 3 | + * https://leetcode.com/problems/escape-a-large-maze/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid |
| 7 | + * square are (x, y). |
| 8 | + * |
| 9 | + * We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. |
| 10 | + * There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents |
| 11 | + * a blocked square with coordinates (xi, yi). |
| 12 | + * |
| 13 | + * Each move, we can walk one square north, east, south, or west if the square is not in |
| 14 | + * the array of blocked squares. We are also not allowed to walk outside of the grid. |
| 15 | + * |
| 16 | + * Return true if and only if it is possible to reach the target square from the source |
| 17 | + * square through a sequence of valid moves. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[][]} blocked |
| 22 | + * @param {number[]} source |
| 23 | + * @param {number[]} target |
| 24 | + * @return {boolean} |
| 25 | + */ |
| 26 | +var isEscapePossible = function(blocked, source, target) { |
| 27 | + const MAX = 1e6; |
| 28 | + const LIMIT = 19900; |
| 29 | + const blockedSet = new Set(blocked.map(([x, y]) => `${x},${y}`)); |
| 30 | + |
| 31 | + if (!helper(source, target)) { |
| 32 | + return false; |
| 33 | + } |
| 34 | + |
| 35 | + return helper(target, source); |
| 36 | + |
| 37 | + function helper(start, goal) { |
| 38 | + const queue = [start]; |
| 39 | + const visited = new Set([`${start[0]},${start[1]}`]); |
| 40 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; |
| 41 | + |
| 42 | + while (queue.length && visited.size <= LIMIT) { |
| 43 | + const [x, y] = queue.shift(); |
| 44 | + |
| 45 | + for (const [dx, dy] of directions) { |
| 46 | + const newX = x + dx; |
| 47 | + const newY = y + dy; |
| 48 | + const key = `${newX},${newY}`; |
| 49 | + |
| 50 | + if (newX < 0 || newX >= MAX || newY < 0 || newY >= MAX |
| 51 | + || blockedSet.has(key) || visited.has(key)) { |
| 52 | + continue; |
| 53 | + } |
| 54 | + |
| 55 | + if (newX === goal[0] && newY === goal[1]) { |
| 56 | + return true; |
| 57 | + } |
| 58 | + |
| 59 | + queue.push([newX, newY]); |
| 60 | + visited.add(key); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return visited.size > LIMIT; |
| 65 | + } |
| 66 | +}; |
0 commit comments