From ad01cb36900445217a038f67869265af91ab5f9e Mon Sep 17 00:00:00 2001 From: Dale Seo <5466341+DaleSeo@users.noreply.github.com> Date: Sat, 8 Aug 2026 12:08:04 -0400 Subject: [PATCH] number-of-islands --- number-of-islands/DaleSeo.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 number-of-islands/DaleSeo.rs diff --git a/number-of-islands/DaleSeo.rs b/number-of-islands/DaleSeo.rs new file mode 100644 index 0000000000..cf12f80805 --- /dev/null +++ b/number-of-islands/DaleSeo.rs @@ -0,0 +1,34 @@ +// TC: O(m * n) +// SC: O(m * n) +impl Solution { + pub fn num_islands(mut grid: Vec>) -> i32 { + let mut cnt = 0; + for r in 0..grid.len() { + for c in 0..grid[r].len() { + if grid[r][c] == '1' { + cnt += 1; + Self::sink(&mut grid, r, c); + } + } + } + cnt + } + + fn sink(grid: &mut Vec>, row: usize, col: usize) { + grid[row][col] = '0'; + let mut stack = vec![(row, col)]; + while let Some((row, col)) = stack.pop() { + for (r, c) in [ + (row, col.wrapping_sub(1)), + (row, col + 1), + (row.wrapping_sub(1), col), + (row + 1, col), + ] { + if r < grid.len() && c < grid[r].len() && grid[r][c] == '1' { + grid[r][c] = '0'; + stack.push((r, c)); + } + } + } + } +}