|
| 1 | +/** |
| 2 | + * 417. Pacific Atlantic Water Flow |
| 3 | + * https://leetcode.com/problems/pacific-atlantic-water-flow/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. |
| 7 | + * The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches |
| 8 | + * the island's right and bottom edges. |
| 9 | + * |
| 10 | + * The island is partitioned into a grid of square cells. You are given an m x n integer |
| 11 | + * matrix heights where heights[r][c] represents the height above sea level of the cell |
| 12 | + * at coordinate (r, c). |
| 13 | + * |
| 14 | + * The island receives a lot of rain, and the rain water can flow to neighboring cells directly |
| 15 | + * north, south, east, and west if the neighboring cell's height is less than or equal to the |
| 16 | + * current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. |
| 17 | + * |
| 18 | + * Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water |
| 19 | + * can flow from cell (ri, ci) to both the Pacific and Atlantic oceans. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[][]} heights |
| 24 | + * @return {number[][]} |
| 25 | + */ |
| 26 | +var pacificAtlantic = function(heights) { |
| 27 | + const result = []; |
| 28 | + const pacific = new Set(); |
| 29 | + const atlantic = new Set(); |
| 30 | + |
| 31 | + for (let i = 0; i < heights.length; i++) { |
| 32 | + dfs(i, 0, pacific); |
| 33 | + dfs(i, heights[0].length - 1, atlantic); |
| 34 | + } |
| 35 | + for (let j = 0; j < heights[0].length; j++) { |
| 36 | + dfs(0, j, pacific); |
| 37 | + dfs(heights.length - 1, j, atlantic); |
| 38 | + } |
| 39 | + |
| 40 | + for (let i = 0; i < heights.length; i++) { |
| 41 | + for (let j = 0; j < heights[0].length; j++) { |
| 42 | + const key = `${i},${j}`; |
| 43 | + if (pacific.has(key) && atlantic.has(key)) { |
| 44 | + result.push([i, j]); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return result; |
| 50 | + |
| 51 | + function dfs(r, c, ocean) { |
| 52 | + const key = `${r},${c}`; |
| 53 | + if (ocean.has(key)) return; |
| 54 | + ocean.add(key); |
| 55 | + |
| 56 | + [[r - 1, c], [r + 1, c], [r, c - 1], [r, c + 1]].forEach(([nr, nc]) => { |
| 57 | + if (nr >= 0 && nr < heights.length && nc >= 0 && nc < heights[0].length |
| 58 | + && heights[nr][nc] >= heights[r][c]) { |
| 59 | + dfs(nr, nc, ocean); |
| 60 | + } |
| 61 | + }); |
| 62 | + } |
| 63 | +}; |
0 commit comments