|
| 1 | +/** |
| 2 | + * 1391. Check if There is a Valid Path in a Grid |
| 3 | + * https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] |
| 7 | + * can be: |
| 8 | + * - 1 which means a street connecting the left cell and the right cell. |
| 9 | + * - 2 which means a street connecting the upper cell and the lower cell. |
| 10 | + * - 3 which means a street connecting the left cell and the lower cell. |
| 11 | + * - 4 which means a street connecting the right cell and the lower cell. |
| 12 | + * - 5 which means a street connecting the left cell and the upper cell. |
| 13 | + * - 6 which means a street connecting the right cell and the upper cell. |
| 14 | + * |
| 15 | + * You will initially start at the street of the upper-left cell (0, 0). A valid path in the |
| 16 | + * grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right |
| 17 | + * cell (m - 1, n - 1). The path should only follow the streets. |
| 18 | + * |
| 19 | + * Notice that you are not allowed to change any street. |
| 20 | + * |
| 21 | + * Return true if there is a valid path in the grid or false otherwise. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[][]} grid |
| 26 | + * @return {boolean} |
| 27 | + */ |
| 28 | +var hasValidPath = function(grid) { |
| 29 | + const rows = grid.length; |
| 30 | + const cols = grid[0].length; |
| 31 | + const directions = { |
| 32 | + 1: [[0, -1, [1, 4, 6]], [0, 1, [1, 3, 5]]], |
| 33 | + 2: [[-1, 0, [2, 3, 4]], [1, 0, [2, 5, 6]]], |
| 34 | + 3: [[0, -1, [1, 4, 6]], [1, 0, [2, 5, 6]]], |
| 35 | + 4: [[0, 1, [1, 3, 5]], [1, 0, [2, 5, 6]]], |
| 36 | + 5: [[0, -1, [1, 4, 6]], [-1, 0, [2, 3, 4]]], |
| 37 | + 6: [[0, 1, [1, 3, 5]], [-1, 0, [2, 3, 4]]] |
| 38 | + }; |
| 39 | + |
| 40 | + return explorePath(0, 0); |
| 41 | + |
| 42 | + function isValid(x, y) { |
| 43 | + return x >= 0 && x < rows && y >= 0 && y < cols; |
| 44 | + } |
| 45 | + |
| 46 | + function explorePath(x, y, visited = new Set()) { |
| 47 | + if (!isValid(x, y) || visited.has(`${x},${y}`)) return false; |
| 48 | + if (x === rows - 1 && y === cols - 1) return true; |
| 49 | + |
| 50 | + visited.add(`${x},${y}`); |
| 51 | + const street = grid[x][y]; |
| 52 | + |
| 53 | + for (const [dx, dy, validStreets] of directions[street]) { |
| 54 | + const newX = x + dx; |
| 55 | + const newY = y + dy; |
| 56 | + if (isValid(newX, newY) && validStreets.includes(grid[newX][newY])) { |
| 57 | + if (explorePath(newX, newY, visited)) return true; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return false; |
| 62 | + } |
| 63 | +}; |
0 commit comments