|
| 1 | +/** |
| 2 | + * @param {number[][]} matrix |
| 3 | + * @return {number[][]} |
| 4 | + */ |
| 5 | +const pacificAtlantic = function(matrix) { |
| 6 | + const res = [] |
| 7 | + if (!matrix || matrix.length === 0 || matrix[0].length === 0) return res |
| 8 | + const rows = matrix.length |
| 9 | + const cols = matrix[0].length |
| 10 | + const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]] |
| 11 | + const pacific = Array.from({ length: rows }, () => new Array(cols).fill(false)) |
| 12 | + const atlantic = Array.from({ length: rows }, () => new Array(cols).fill(false)) |
| 13 | + for (let y = 0; y < rows; y++) { |
| 14 | + helper(0, y, pacific, -1, matrix, cols, rows, dirs) |
| 15 | + helper(cols - 1, y, atlantic, -1, matrix, cols, rows, dirs) |
| 16 | + } |
| 17 | + for (let x = 0; x < cols; x++) { |
| 18 | + helper(x, 0, pacific, -1, matrix, cols, rows, dirs) |
| 19 | + helper(x, rows - 1, atlantic, -1, matrix, cols, rows, dirs) |
| 20 | + } |
| 21 | + |
| 22 | + for (let y = 0; y < rows; y++) { |
| 23 | + for (let x = 0; x < cols; x++) { |
| 24 | + if (pacific[y][x] && atlantic[y][x]) { |
| 25 | + res.push([y, x]) |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + return res |
| 30 | +} |
| 31 | + |
| 32 | +function helper(x, y, visited, height, matrix, cols, rows, dirs) { |
| 33 | + if (x < 0 || x >= cols || y < 0 || y >= rows || visited[y][x] || matrix[y][x] < height) return |
| 34 | + visited[y][x] = true |
| 35 | + for (let dir of dirs) |
| 36 | + helper(x + dir[0], y + dir[1], visited, matrix[y][x], matrix, cols, rows, dirs) |
| 37 | +} |
0 commit comments