LeetCode 200. Number of Islands

Problem Statement


use std::collections::HashMap;

impl Solution {
fn dfs(grid: &mut Vec<Vec<char>>, x: i32, y: i32) {
let (m, n) = (grid.len(), grid[0].len());
let (dx, dy) = ([1, -1, 0, 0], [0, 0, 1, -1]);
for i in 0..4 {
let (xx, yy) = (x + dx[i], y + dy[i]);
if xx < 0 || xx >= m as i32 || yy < 0 || yy >= n as i32 ||
grid[xx as usize][yy as usize] == '0' {
continue;
}
grid[xx as usize][yy as usize] = '0';
Self::dfs(grid, xx, yy);
}
}
pub fn num_islands(grid: Vec<Vec<char>>) -> i32 {
if grid.is_empty() {
return 0;
}
let mut g = grid.clone();
let (m, n, mut ans) = (grid.len(), grid[0].len(), 0);

for i in 0..m {
for j in 0..n {
if g[i][j] == '1' {
ans += 1;
Self::dfs(&mut g, i as i32, j as i32);
}
}
}

return ans;
}
}