|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * brainstorming: |
| 4 | + * bfs + memoization |
| 5 | + * |
| 6 | + * n = length of height |
| 7 | + * m = length of height[i] |
| 8 | + * time complexity: O(n*m * 4^n*m) |
| 9 | + * space complexity: O(n*m) |
| 10 | + */ |
| 11 | +var pacificAtlantic = function (heights) { |
| 12 | + const visited = Array.from({ length: heights.length }, (_, i) => |
| 13 | + Array.from({ length: heights[i].length }, () => false) |
| 14 | + ); |
| 15 | + const memo = new Map(); |
| 16 | + |
| 17 | + const bfs = (row, column) => { |
| 18 | + const dr = [0, 0, -1, 1]; |
| 19 | + const dc = [1, -1, 0, 0]; |
| 20 | + const queue = [[row, column]]; |
| 21 | + let [pacific, atlantic] = [false, false]; |
| 22 | + let queueIndex = 0; |
| 23 | + |
| 24 | + while (queueIndex !== queue.length) { |
| 25 | + const currentLastLength = queue.length; |
| 26 | + |
| 27 | + while (queueIndex !== currentLastLength) { |
| 28 | + const [r, c] = queue[queueIndex++]; |
| 29 | + visited[r][c] = `${row},${column}`; |
| 30 | + |
| 31 | + if (memo.has(`${r},${c}`)) { |
| 32 | + memo.set(`${row},${column}`, [row, column]); |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + for (let i = 0; i < 4; i++) { |
| 37 | + const nextR = r + dr[i]; |
| 38 | + const nextC = c + dc[i]; |
| 39 | + const isPacific = nextR === -1 || nextC === -1; |
| 40 | + const isAtlantic = |
| 41 | + nextR === heights.length || nextC === heights[0].length; |
| 42 | + |
| 43 | + if (isPacific) { |
| 44 | + pacific = true; |
| 45 | + continue; |
| 46 | + } |
| 47 | + if (isAtlantic) { |
| 48 | + atlantic = true; |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + if (visited[nextR][nextC] === `${row},${column}`) continue; |
| 53 | + |
| 54 | + if (heights[r][c] < heights[nextR][nextC]) continue; |
| 55 | + |
| 56 | + queue.push([nextR, nextC]); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + if (pacific && atlantic) { |
| 61 | + memo.set(`${row},${column}`, [row, column]); |
| 62 | + return; |
| 63 | + } |
| 64 | + } |
| 65 | + }; |
| 66 | + |
| 67 | + for (let row = 0; row < heights.length; row++) { |
| 68 | + for (let column = 0; column < heights[row].length; column++) { |
| 69 | + bfs(row, column); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return [...memo.values()]; |
| 74 | +}; |
0 commit comments