[LeetCode] Pacific Atlantic Water Flow

417. Pacific Atlantic Water Flow

Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the “Pacific ocean” touches the left and top edges of the matrix and the “Atlantic ocean” touches the right and bottom edges.

Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.

Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.

Note:

  • The order of returned grid coordinates does not matter.
  • Both m and n are less than 150.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};

void bfs(vector<vector<int>> &m, vector<vector<bool>> &v, int &h, int &w, bool flag) {
queue<pair<int, int>> q;
if(flag) {
for(int i = 0; i < w; i++) {
v[0][i] = true;
q.push({0, i});
}
for(int i = 0; i < h; i++) {
v[i][0] = true;
q.push({i, 0});
}
} else {
for(int i = 0; i < w; i++) {
v[h - 1][i] = true;
q.push({h - 1, i});
}
for(int i = 0; i < h; i++) {
v[i][w - 1] = true;
q.push({i, w - 1});
}
}

while(!q.empty()) {
auto p = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int ny = p.first + dy[i];
int nx = p.second + dx[i];
if(0 <= nx && nx < w && 0 <= ny && ny < h && !v[ny][nx] && m[p.first][p.second] <= m[ny][nx]) {
q.push({ny, nx});
v[ny][nx] = true;
}
}
}

return;
}
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {
vector<vector<int>> res;
if(matrix.empty() || matrix[0].empty()) return res;

int h = matrix.size(), w = matrix[0].size();
vector<vector<bool>> pacific(h, vector<bool>(w, false)), atlantic(h, vector<bool>(w, false));

bfs(matrix, pacific, h, w, true);
bfs(matrix, atlantic, h, w, false);

for(int i = 0; i < h; i++)
for(int j = 0; j < w; j++)
if(pacific[i][j] && atlantic[i][j])
res.push_back(vector<int>{i, j});

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/25/PS/LeetCode/pacific-atlantic-water-flow/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.