-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnumber-of-islands.rs
46 lines (35 loc) · 1.04 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
#![allow(dead_code, unused, unused_variables)]
fn main() {}
struct Solution;
impl Solution {
pub fn num_islands(grid: Vec<Vec<char>>) -> i32 {
let mut grid = grid;
let mut r = 0;
for i in 0..grid.len() {
for j in 0..grid[0].len() {
if grid[i][j] == '1' {
r += 1;
Self::change_1_to_0(&mut grid, (i, j));
}
}
}
r
}
fn change_1_to_0(grid: &mut Vec<Vec<char>>, index: (usize, usize)) {
if index.0 == grid.len() || index.1 == grid[0].len() {
return;
}
if grid[index.0][index.1] == '0' {
return;
}
grid[index.0][index.1] = '0';
Self::change_1_to_0(grid, (index.0 + 1, index.1));
Self::change_1_to_0(grid, (index.0, index.1 + 1));
if index.0 > 0 {
Self::change_1_to_0(grid, (index.0 - 1, index.1));
}
if index.1 > 0 {
Self::change_1_to_0(grid, (index.0, index.1 - 1));
}
}
}