-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path113-pacific-atlantic-water-flow.cs
More file actions
65 lines (52 loc) · 1.78 KB
/
113-pacific-atlantic-water-flow.cs
File metadata and controls
65 lines (52 loc) · 1.78 KB
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
62
63
64
65
public class Solution {
int ROWS;
int COLS;
(int,int)[] dirs = [(0,1),(0,-1),(-1,0),(1,0)];
bool WithinBounds(int i, int j) {
return i < ROWS && i >= 0 && j < COLS && j >= 0;
}
public IList<IList<int>> PacificAtlantic(int[][] heights) {
ROWS = heights.Length;
COLS = heights[0].Length;
if(ROWS == COLS && COLS == 1) return [[0,0]];
var result = new List<IList<int>>();
// reachable trackers
var pr = new HashSet<(int,int)>();
var ar = new HashSet<(int,int)>();
// bfs queues
var pq = new Queue<(int,int)>();
var aq = new Queue<(int,int)>();
for(int i = 0; i < ROWS; i++){
pq.Enqueue((i,0));
aq.Enqueue((i,COLS-1));
pr.Add((i,0));
ar.Add((i,COLS-1));
}
for(int j = 0; j < COLS ; j++){
pq.Enqueue((0,j));
aq.Enqueue((ROWS-1,j));
pr.Add((0,j));
ar.Add((ROWS-1,j));
}
// do pacific side reverse traversal
Bfs(pq,pr,heights);
// do atlantic side reverse traversal
Bfs(aq,ar,heights);
return pr.Where(e => ar.Contains(e))
.Select(e => (IList<int>)new List<int> { e.Item1, e.Item2 })
.ToList<IList<int>>();
}
void Bfs(Queue<(int,int)> q, HashSet<(int,int)> r, int[][] h){
while(q.Count > 0){
(int i, int j) e = q.Dequeue();
foreach(var dir in dirs){
(int x, int y) n = dir;
(int x, int y) ne = (e.i + n.x, e.j + n.y);
if(!r.Contains(ne) && WithinBounds(ne.x, ne.y) && h[e.i][e.j] <= h[ne.x][ne.y]){
q.Enqueue(ne);
r.Add(ne);
}
}
}
}
}