Pacific Atlantic Water Flow — Reverse BFS from Both Oceans
Advertisement
Problem 287 · Pacific Atlantic Water Flow
Difficulty: Medium · Pattern: Reverse Multi-Source BFS
Water flows from high to low. Cells that can reach both oceans = intersection of reverse-BFS from each shore.
Solutions
# Python
from collections import deque
def pacificAtlantic(heights):
m, n = len(heights), len(heights[0])
dirs = [(0,1),(0,-1),(1,0),(-1,0)]
def bfs(starts):
visited = set(starts)
queue = deque(starts)
while queue:
r, c = queue.popleft()
for dr, dc in dirs:
nr, nc = r+dr, c+dc
if 0<=nr<m and 0<=nc<n and (nr,nc) not in visited and heights[nr][nc]>=heights[r][c]:
visited.add((nr,nc)); queue.append((nr,nc))
return visited
pacific = [(0,c) for c in range(n)] + [(r,0) for r in range(m)]
atlantic = [(m-1,c) for c in range(n)] + [(r,n-1) for r in range(m)]
return list(bfs(pacific) & bfs(atlantic))
// Java
public List<List<Integer>> pacificAtlantic(int[][] heights) {
int m=heights.length, n=heights[0].length;
boolean[][] pac=new boolean[m][n], atl=new boolean[m][n];
Queue<int[]> pq=new LinkedList<>(), aq=new LinkedList<>();
for (int r=0;r<m;r++) { pq.offer(new int[]{r,0}); pac[r][0]=true; aq.offer(new int[]{r,n-1}); atl[r][n-1]=true; }
for (int c=0;c<n;c++) { pq.offer(new int[]{0,c}); pac[0][c]=true; aq.offer(new int[]{m-1,c}); atl[m-1][c]=true; }
bfs(heights,pq,pac,m,n); bfs(heights,aq,atl,m,n);
List<List<Integer>> res=new ArrayList<>();
for (int r=0;r<m;r++) for (int c=0;c<n;c++) if (pac[r][c]&&atl[r][c]) res.add(Arrays.asList(r,c));
return res;
}
void bfs(int[][] h, Queue<int[]> q, boolean[][] vis, int m, int n) {
int[][] dirs={{0,1},{0,-1},{1,0},{-1,0}};
while (!q.isEmpty()) {
int[] cur=q.poll();
for (int[] d:dirs) { int nr=cur[0]+d[0],nc=cur[1]+d[1];
if (nr>=0&&nr<m&&nc>=0&&nc<n&&!vis[nr][nc]&&h[nr][nc]>=h[cur[0]][cur[1]]) { vis[nr][nc]=true; q.offer(new int[]{nr,nc}); }
}
}
}
Complexity
- Time: O(m*n)
- Space: O(m*n)
Advertisement