-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.rs
72 lines (67 loc) · 1.86 KB
/
main.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
71
72
fn main() {
println!("Hello, world!");
}
struct Solution {}
impl Solution {
pub fn closed_island(mut grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
for i in 0..m {
Self::into1(&mut grid, i, 0);
Self::into1(&mut grid, i, n - 1);
}
for j in 0..n {
Self::into1(&mut grid, 0, j);
Self::into1(&mut grid, m - 1, j);
}
let mut res = 0;
for i in 1..m-1 {
for j in 1.. n-1 {
if grid[i][j] == 0 {
// if is land
res += 1;
Self::into1(&mut grid, i, j);
}
}
}
res
}
pub fn into1(grid: &mut Vec<Vec<i32>>, i: usize, j: usize) {
if grid[i][j] == 1 { return }
grid[i][j] = 1;
let m = grid.len();
let n = grid[0].len();
if i >= 1 { Self::into1(grid, i - 1, j) }
if i + 1 < m { Self::into1(grid, i + 1, j) }
if j >= 1 { Self::into1(grid, i, j - 1) }
if j + 1 < n { Self::into1(grid, i, j + 1) }
}
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn basic() {
assert_eq!(Solution::closed_island(vec![
vec![1,1,1,1,1,1,1,0],
vec![1,0,0,0,0,1,1,0],
vec![1,0,1,0,1,1,1,0],
vec![1,0,0,0,0,1,0,1],
vec![1,1,1,1,1,1,1,0]
]), 2);
assert_eq!(Solution::closed_island(vec![
vec![0,0,1,0,0],
vec![0,1,0,1,0],
vec![0,1,1,1,0]
]), 1);
assert_eq!(Solution::closed_island(vec![
vec![1,1,1,1,1,1,1],
vec![1,0,0,0,0,0,1],
vec![1,0,1,1,1,0,1],
vec![1,0,1,0,1,0,1],
vec![1,0,1,1,1,0,1],
vec![1,0,0,0,0,0,1],
vec![1,1,1,1,1,1,1]
]), 2);
}
}