|
| 1 | +// Runtime 117 ms Beats 81.9% Memory 51.5 MB Beats 48.34% |
| 2 | +/** |
| 3 | + * @param {number[][]} heights |
| 4 | + * @return {number[][]} |
| 5 | + */ |
| 6 | +const pacificAtlantic = (heights) => { |
| 7 | + if (heights.length === 0 || heights[0].length === 0) { |
| 8 | + return []; |
| 9 | + } |
| 10 | + |
| 11 | + const m = heights.length; |
| 12 | + const n = heights[0].length; |
| 13 | + |
| 14 | + const pacificQueue = []; // Queue for cells that can flow to the Pacific Ocean |
| 15 | + const atlanticQueue = []; // Queue for cells that can flow to the Atlantic Ocean |
| 16 | + |
| 17 | + // Initialize visited arrays for both oceans |
| 18 | + const pacificVisited = Array.from({ length: m }, () => new Array(n).fill(false)); |
| 19 | + const atlanticVisited = Array.from({ length: m }, () => new Array(n).fill(false)); |
| 20 | + |
| 21 | + // Add border cells to the respective queues and mark them as visited |
| 22 | + for (let i = 0; i < m; i++) { |
| 23 | + pacificQueue.push([i, 0]); |
| 24 | + atlanticQueue.push([i, n - 1]); |
| 25 | + pacificVisited[i][0] = true; |
| 26 | + atlanticVisited[i][n - 1] = true; |
| 27 | + } |
| 28 | + for (let j = 0; j < n; j++) { |
| 29 | + pacificQueue.push([0, j]); |
| 30 | + atlanticQueue.push([m - 1, j]); |
| 31 | + pacificVisited[0][j] = true; |
| 32 | + atlanticVisited[m - 1][j] = true; |
| 33 | + } |
| 34 | + |
| 35 | + // Perform BFS from the Pacific Ocean |
| 36 | + bfs(pacificQueue, pacificVisited, heights); |
| 37 | + |
| 38 | + // Perform BFS from the Atlantic Ocean |
| 39 | + bfs(atlanticQueue, atlanticVisited, heights); |
| 40 | + |
| 41 | + // Find cells that can flow to both oceans |
| 42 | + const result = []; |
| 43 | + for (let i = 0; i < m; i++) { |
| 44 | + for (let j = 0; j < n; j++) { |
| 45 | + if (pacificVisited[i][j] && atlanticVisited[i][j]) { |
| 46 | + result.push([i, j]); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return result; |
| 52 | +}; |
| 53 | + |
| 54 | +const bfs = (queue, visited, heights) => { |
| 55 | + const m = heights.length; |
| 56 | + const n = heights[0].length; |
| 57 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // Right, Down, Left, Up |
| 58 | + |
| 59 | + while (queue.length > 0) { |
| 60 | + const [row, col] = queue.shift(); |
| 61 | + |
| 62 | + for (const [dx, dy] of directions) { |
| 63 | + const newRow = row + dx; |
| 64 | + const newCol = col + dy; |
| 65 | + |
| 66 | + // Check if the new cell is within bounds |
| 67 | + if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n) { |
| 68 | + // Check if the new cell is unvisited and its height is not greater than the current cell |
| 69 | + if (!visited[newRow][newCol] && heights[newRow][newCol] >= heights[row][col]) { |
| 70 | + visited[newRow][newCol] = true; |
| 71 | + queue.push([newRow, newCol]); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | +}; |
0 commit comments