-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path417.pacific-atlantic-water-flow.cpp
54 lines (47 loc) · 1.62 KB
/
417.pacific-atlantic-water-flow.cpp
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
class Solution {
public:
int max_row, max_col;
vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {
vector<vector<int>> r;
int m = matrix.size();
if (m == 0)
return r;
int n = matrix[0].size();
if (n == 0)
return r;
vector<vector<bool>> pacific(m, vector<bool>(n));
vector<vector<bool>> atlantic(m, vector<bool>(n));
for (int i = 0; i < m; i++) {
dfs(matrix, pacific, i, 0);
dfs(matrix, atlantic, i, n-1);
}
for (int j = 0; j < n; j++) {
dfs(matrix, pacific, 0, j);
dfs(matrix, atlantic, m-1, j);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j])
r.push_back({i,j});
}
}
return r;
}
void dfs(vector<vector<int>>& matrix, vector<vector<bool>>& visited, int i, int j) {
int m = matrix.size();
int n = matrix[0].size();
visited[i][j] = true;
//up
if (i-1 >= 0 && visited[i-1][j] != true && matrix[i-1][j]>=matrix[i][j])
dfs(matrix, visited, i-1, j);
//down
if (i+1 < m && visited[i+1][j] != true && matrix[i+1][j]>=matrix[i][j])
dfs(matrix, visited, i+1, j);
//left
if (j-1 >= 0 && visited[i][j-1] != true && matrix[i][j-1]>=matrix[i][j])
dfs(matrix, visited, i, j-1);
//right
if (j+1 <n && visited[i][j+1] != true && matrix[i][j+1]>=matrix[i][j])
dfs(matrix, visited, i, j+1);
}
};