diff --git a/src/problem/mod.rs b/src/problem/mod.rs index ee4c0f9..1c2c0c7 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -153,4 +153,5 @@ mod p199_binary_tree_right_side_view; mod p637_average_of_levels_in_binary_tree; mod p530_minimum_absolute_difference_in_bst; mod p230_kth_smallest_element_in_a_bst; -mod p98_validate_binary_search_tree; \ No newline at end of file +mod p98_validate_binary_search_tree; +mod p200_number_of_islands; \ No newline at end of file diff --git a/src/problem/p200_number_of_islands.rs b/src/problem/p200_number_of_islands.rs new file mode 100644 index 0000000..58bd113 --- /dev/null +++ b/src/problem/p200_number_of_islands.rs @@ -0,0 +1,61 @@ +/** + * [200] Number of Islands + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + fn is_in_grid(x: i32, y: i32, grid: &Vec>) -> bool { + let m = grid.len() as i32; + let n = grid[0].len() as i32; + + x >= 0 && x < m && y >= 0 && y < n + } + + fn dfs(grid: &mut Vec>, x: i32, y: i32) { + if !Self::is_in_grid(x, y, grid) { + return; + } + + if grid[x as usize][y as usize] != '1' { + return; + } + grid[x as usize][y as usize] = '2'; + + Self::dfs(grid, x - 1, y); + Self::dfs(grid, x + 1, y); + Self::dfs(grid, x, y + 1); + Self::dfs(grid, x, y - 1); + } + + pub fn num_islands(grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + let mut result = 0; + let mut grid = grid; + + for i in 0..m { + for j in 0..n { + if grid[i][j] == '1' { + result += 1; + Self::dfs(&mut grid, i as i32, j as i32); + } + } + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_200() { + } +}