Skip to content

Commit 2fd4532

Browse files
committed
Used dfs for solving pacific atlantic water flow
1 parent ff70c02 commit 2fd4532

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

417/main.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//https://dev.to/seanpgallivan/solution-pacific-atlantic-water-flow-4lb3
2+
// https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1127040/Rust-DFS-solution
3+
impl Solution {
4+
pub fn pacific_atlantic(heights: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
5+
if heights.is_empty(){
6+
return Vec::new();
7+
}
8+
let (m,n) = (heights.len(),heights[0].len());
9+
let mut p_reachable = vec![vec![false;n];m];
10+
let mut a_reachable = vec![vec![false;n];m];
11+
for i in 0..m {
12+
Self::dfs(&mut p_reachable, &heights, (i,0));
13+
Self::dfs(&mut a_reachable, &heights, (i,n-1));
14+
}
15+
for j in 0..n{
16+
Self::dfs(&mut p_reachable, &heights, (0,j));
17+
Self::dfs(&mut a_reachable, &heights, (m-1,j));
18+
}
19+
let mut answers :Vec<Vec<i32>> = Vec::new();
20+
for i in 0..m {
21+
for j in 0..n {
22+
if p_reachable[i][j] && a_reachable[i][j] {
23+
answers.push([i as i32,j as i32].to_vec());
24+
}
25+
}
26+
}
27+
answers
28+
29+
}
30+
fn dfs(reachable: &mut Vec<Vec<bool>>,matrix: &Vec<Vec<i32>>,(i,j): (usize,usize)) {
31+
reachable[i][j] = true;
32+
for &(di,dj) in &[(-1,0),(0,-1),(1,0),(0,1)] {
33+
let ni = di + i as i32;
34+
let nj = dj + j as i32;
35+
if (0..matrix.len() as i32).contains(&ni) && (0..matrix[0].len() as i32).contains(&nj) && !reachable[ni as usize][nj as usize] && matrix[ni as usize][nj as usize] >= matrix[i][j] {
36+
Self::dfs(reachable,&matrix,(ni as usize, nj as usize));
37+
}
38+
39+
}
40+
}
41+
42+
}

0 commit comments

Comments
 (0)