|
| 1 | +/** |
| 2 | + * 980. Unique Paths III |
| 3 | + * https://leetcode.com/problems/unique-paths-iii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an m x n integer array grid where grid[i][j] could be: |
| 7 | + * - 1 representing the starting square. There is exactly one starting square. |
| 8 | + * - 2 representing the ending square. There is exactly one ending square. |
| 9 | + * - 0 representing empty squares we can walk over. |
| 10 | + * - -1 representing obstacles that we cannot walk over. |
| 11 | + * |
| 12 | + * Return the number of 4-directional walks from the starting square to the ending |
| 13 | + * square, that walk over every non-obstacle square exactly once. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[][]} grid |
| 18 | + * @return {number} |
| 19 | + */ |
| 20 | +var uniquePathsIII = function(grid) { |
| 21 | + const rows = grid.length; |
| 22 | + const cols = grid[0].length; |
| 23 | + let emptySquares = 0; |
| 24 | + let startRow; |
| 25 | + let startCol; |
| 26 | + |
| 27 | + for (let i = 0; i < rows; i++) { |
| 28 | + for (let j = 0; j < cols; j++) { |
| 29 | + if (grid[i][j] === 0) emptySquares++; |
| 30 | + if (grid[i][j] === 1) [startRow, startCol] = [i, j]; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + function explorePaths(row, col, remaining) { |
| 35 | + if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] < 0) { |
| 36 | + return 0; |
| 37 | + } |
| 38 | + if (grid[row][col] === 2) { |
| 39 | + return remaining === 0 ? 1 : 0; |
| 40 | + } |
| 41 | + |
| 42 | + const current = grid[row][col]; |
| 43 | + grid[row][col] = -1; |
| 44 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; |
| 45 | + let pathCount = 0; |
| 46 | + |
| 47 | + for (const [dr, dc] of directions) { |
| 48 | + pathCount += explorePaths(row + dr, col + dc, remaining - 1); |
| 49 | + } |
| 50 | + |
| 51 | + grid[row][col] = current; |
| 52 | + return pathCount; |
| 53 | + } |
| 54 | + |
| 55 | + return explorePaths(startRow, startCol, emptySquares + 1); |
| 56 | +}; |
0 commit comments