From 96d3ceac2992b94b181e2410e36785fe34616eb7 Mon Sep 17 00:00:00 2001 From: Luca Lombardo Date: Thu, 30 Nov 2023 18:10:24 +0100 Subject: [PATCH] number of islands problem solved --- .gitignore | 1 + 2023_11_30/x-total-shapes/Cargo.toml | 8 ++++ 2023_11_30/x-total-shapes/src/main.rs | 65 +++++++++++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 2023_11_30/x-total-shapes/Cargo.toml create mode 100644 2023_11_30/x-total-shapes/src/main.rs diff --git a/.gitignore b/.gitignore index c8ed7b7..9b000fd 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ debug/ target/ hands-on_01/ +hands-on_02/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html diff --git a/2023_11_30/x-total-shapes/Cargo.toml b/2023_11_30/x-total-shapes/Cargo.toml new file mode 100644 index 0000000..bfd4d4e --- /dev/null +++ b/2023_11_30/x-total-shapes/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "x-total-shapes" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/2023_11_30/x-total-shapes/src/main.rs b/2023_11_30/x-total-shapes/src/main.rs new file mode 100644 index 0000000..decf561 --- /dev/null +++ b/2023_11_30/x-total-shapes/src/main.rs @@ -0,0 +1,65 @@ +struct Solution; + +impl Solution { + pub fn dfs(grid: &mut Vec>, 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 { Self::dfs(grid, i - 1, j); } + if j > 0 { Self::dfs(grid, i, j - 1); } + Self::dfs(grid, i + 1, j); + Self::dfs(grid, i, j + 1); + } + + pub fn num_islands(grid: &mut Vec>) -> i32 { + let mut count = 0; + let rows = grid.len(); + let cols = grid[0].len(); + + for i in 0..rows { + for j in 0..cols { + if grid[i][j] == '1' { + Self::dfs(grid, i, j); + count += 1; + } + } + } + count + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test1() { + let mut grid1 = 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'], + ]; + assert_eq!(Solution::num_islands(&mut grid1), 1); + } + + #[test] + fn test2() { + let mut grid2 = 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'], + ]; + assert_eq!(Solution::num_islands(&mut grid2), 3); + } +} + +fn main() { +}