-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path463.island-perimeter.rs
71 lines (59 loc) · 1.63 KB
/
463.island-perimeter.rs
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
66
67
68
69
70
/*
* @lc app=leetcode id=463 lang=rust
*
* [463] Island Perimeter
*/
// @lc code=start
use std::collections::HashSet;
impl Solution {
pub fn island_perimeter(grid: Vec<Vec<i32>>) -> i32 {
let R = grid.len();
if R == 0 { return 0; }
let C = grid[0].len();
let mut seen = HashSet::new();
let mut ans = 0;
fn dfs(
coord: (usize, usize),
seen: &mut HashSet<(usize, usize)>,
R: usize, C: usize,
ans: &mut u32,
grid: &Vec<Vec<i32>>
) {
seen.insert(coord);
let (x, y) = coord;
let mut neis = vec![];
if x > 0 {
neis.push((x-1, y));
} else { *ans += 1; }
if x < R - 1 {
neis.push((x+1, y));
} else { *ans += 1; }
if y > 0 {
neis.push((x, y-1));
} else { *ans += 1; }
if y < C - 1 {
neis.push((x, y+1));
} else { *ans += 1; }
for (i, j) in neis {
if grid[i][j] == 1 {
if !seen.contains(&(i, j)) {
dfs((i, j), seen, R, C, ans, grid);
}
} else {
*ans += 1;
}
}
}
for i in 0..R {
for j in 0..C {
if grid[i][j] == 1 {
if !seen.contains(&(i, j)) {
dfs((i, j), &mut seen, R, C, &mut ans, &grid);
}
}
}
}
ans as i32
}
}
// @lc code=end