-
Notifications
You must be signed in to change notification settings - Fork 0
/
number_of_islands.rs
68 lines (59 loc) · 1.46 KB
/
number_of_islands.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
#![allow(dead_code)]
pub fn num_islands(grid: &mut Vec<Vec<char>>) -> i32 {
if grid.is_empty() {
return 0;
}
let rows = grid.len();
let cols = grid[0].len();
let mut islands = 0;
fn dfs(grid: &mut Vec<Vec<char>>, i: usize, j: usize) {
let rows = grid.len();
let cols = grid[0].len();
if i >= rows || j >= cols || grid[i][j] == '0' {
return;
}
grid[i][j] = '0';
if i > 0 {
dfs(grid, i - 1, j);
}
if j > 0 {
dfs(grid, i, j - 1);
}
dfs(grid, i + 1, j);
dfs(grid, i, j + 1);
}
for i in 0..rows {
for j in 0..cols {
if grid[i][j] == '1' {
islands += 1;
dfs(grid, i, j);
}
}
}
islands
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_num_islands() {
assert_eq!(
num_islands(&mut vec![
vec!['1', '1', '1', '1', '0'],
vec!['1', '1', '0', '1', '0'],
vec!['1', '1', '0', '0', '0'],
vec!['0', '0', '0', '0', '0']
]),
1
);
assert_eq!(
num_islands(&mut vec![
vec!['1', '1', '0', '0', '0'],
vec!['1', '1', '0', '0', '0'],
vec!['0', '0', '1', '0', '0'],
vec!['0', '0', '0', '1', '1']
]),
3
);
}
}