forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0417-pacific-atlantic-water-flow.cpp
61 lines (50 loc) · 1.91 KB
/
0417-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
55
56
57
58
59
60
61
/*
Top & left pacific, bottom & right atlantic, determine spots that flow to both
Instead go outside in, from oceans to spots where rain could flow from
Faster bc avoids repeated work: cells along a path can also reach that ocean
Time: O(m x n)
Space: O(m x n)
*/
class Solution {
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
int m = heights.size();
int n = heights[0].size();
vector<vector<bool>> pacific(m, vector<bool>(n));
vector<vector<bool>> atlantic(m, vector<bool>(n));
for (int i = 0; i < m; i++) {
dfs(heights, pacific, i, 0, m, n);
dfs(heights, atlantic, i, n - 1, m, n);
}
for (int j = 0; j < n; j++) {
dfs(heights, pacific, 0, j, m, n);
dfs(heights, atlantic, m - 1, j, m, n);
}
vector<vector<int>> result;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j]) {
result.push_back({i, j});
}
}
}
return result;
}
private:
void dfs(vector<vector<int>>& heights, vector<vector<bool>>& visited,
int i, int j, int m, int n) {
visited[i][j] = true;
if (i > 0 && !visited[i - 1][j] && heights[i - 1][j] >= heights[i][j]) {
dfs(heights, visited, i - 1, j, m, n);
}
if (i < m - 1 && !visited[i + 1][j] && heights[i + 1][j] >= heights[i][j]) {
dfs(heights, visited, i + 1, j, m, n);
}
if (j > 0 && !visited[i][j - 1] && heights[i][j - 1] >= heights[i][j]) {
dfs(heights, visited, i, j - 1, m, n);
}
if (j < n - 1 && !visited[i][j + 1] && heights[i][j + 1] >= heights[i][j]) {
dfs(heights, visited, i, j + 1, m, n);
}
}
};