There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island’s left and top edges, and the Atlantic Ocean touches the island’s right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell’s height is less than or equal to the current cell’s height. Water can flow from any cell adjacent to an ocean into the ocean.
Return a 2D list of grid coordinatesresultwhereresult[i] = [ri, ci]denotes that rain water can flow from cell(ri, ci)to both the Pacific and Atlantic oceans.
We can see how many points can water flow to pacific point, and how many points can water flow to atlantic oceans. The intersection of these sets will the answer we want.
We can see first row is adjacent to Pacific ocean and last row is adjacent to Atlantic ocean. Likewise, first column is adjacent to pacific ocean and last column is adjacent to Atlantic ocean.
From these points we do BFS, so that we dont visit the same points again and again.
classSolution:
defpacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m, n = len(heights), len(heights[0])
# BFS function to compute reachable cellsdefbfs(starts: List[List[int]]) -> set:
visited = set(starts)
q = deque(starts)
while q:
r, c = q.popleft()
for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)): # Directions (up, right, down, left) x, y = r + dr, c + dc
if0<= x < m and0<= y < n and (x, y) notin visited and heights[x][y] >= heights[r][c]:
visited.add((x, y))
q.append((x, y))
return visited
# Starting points for Pacific and Atlantic pac_starts = [(0, j) for j in range(n)] + [(i, 0) for i in range(m)]
atl_starts = [(m -1, j) for j in range(n)] + [(i, n -1) for i in range(m)]
# Find all cells reachable by each ocean pac_reachable = bfs(pac_starts)
atl_reachable = bfs(atl_starts)
# Intersection of reachable cellsreturn list(pac_reachable & atl_reachable)
Water can flow from a higher or equal height to a lower height cell.
It starts from cells on the edge of the Pacific (left and top edges) and Atlantic (right and bottom edges).
Reverse Simulation:
Instead of simulating water from each cell flowing to the oceans, simulate water flowing inward from the oceans using DFS or BFS.
Use two m x n boolean matrices (pac and atl) to keep track of cells that can reach the respective oceans.
Combine Results:
After performing two DFS/BFS starting from both oceans, find the intersection of cells that can flow to both oceans (i.e., cells marked True in both matrices).
Implementation Steps:
Initialise pac and atl boolean matrices.
Perform DFS/BFS for each ocean, starting from its boundary cells.
Combine results into a list of coordinates that can flow to both oceans.
classSolution {
public List<List<Integer>>pacificAtlantic(int[][] heights) {
int m = heights.length, n = heights[0].length;
boolean[][] pac =newboolean[m][n];
boolean[][] atl =newboolean[m][n];
List<List<Integer>> ans =new ArrayList<>();
for (int i = 0; i < m; i++) {
dfs(heights, pac, i, 0);
dfs(heights, atl, i, n - 1);
}
for (int j = 0; j < n; j++) {
dfs(heights, pac, 0, j);
dfs(heights, atl, m - 1, j);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (pac[i][j]&& atl[i][j]) {
List<Integer> cell =new ArrayList<>();
cell.add(i);
cell.add(j);
ans.add(cell);
}
}
}
return ans;
}
privatevoiddfs(int[][] h, boolean[][] ocean, int r, int c) {
ocean[r][c]=true;
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
for (int[] d : dirs) {
int x = r + d[0], y = c + d[1];
if (x >= 0 && x < h.length&& y >= 0 && y < h[0].length&&!ocean[x][y]&& h[x][y]>= h[r][c]) {
dfs(h, ocean, x, y);
}
}
}
}
classSolution:
defpacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m, n = len(heights), len(heights[0])
pac = [[False] * n for _ in range(m)]
atl = [[False] * n for _ in range(m)]
ans: List[List[int]] = []
defdfs(h: List[List[int]], ocean: List[List[bool]], r: int, c: int) ->None:
ocean[r][c] =Truefor dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
x, y = r + dr, c + dc
if0<= x < m and0<= y < n andnot ocean[x][y] and h[x][y] >= h[r][c]:
dfs(h, ocean, x, y)
for i in range(m):
dfs(heights, pac, i, 0)
dfs(heights, atl, i, n -1)
for j in range(n):
dfs(heights, pac, 0, j)
dfs(heights, atl, m -1, j)
for i in range(m):
for j in range(n):
if pac[i][j] and atl[i][j]:
ans.append([i, j])
return ans