From 64c7dbf1410ff3861bd2b6d3c41b832750609aa0 Mon Sep 17 00:00:00 2001 From: TK Date: Fri, 27 May 2022 23:19:55 -0300 Subject: [PATCH] solve number of islands --- .../number-of-islands/number-of-islands.js | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 coding_interviews/leetcode/medium/number-of-islands/number-of-islands.js diff --git a/coding_interviews/leetcode/medium/number-of-islands/number-of-islands.js b/coding_interviews/leetcode/medium/number-of-islands/number-of-islands.js new file mode 100644 index 00000000..f3932868 --- /dev/null +++ b/coding_interviews/leetcode/medium/number-of-islands/number-of-islands.js @@ -0,0 +1,33 @@ +function isInsideTheGrid(grid, row, col) { + return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length; +} + +function dfs(grid, row, col) { + if (isInsideTheGrid(grid, row, col) && grid[row][col] === '1') { + grid[row][col] = 0; // marked as visited + dfs(grid, row - 1, col); // top + dfs(grid, row + 1, col); // bottom + dfs(grid, row, col - 1); // left + dfs(grid, row, col + 1); // right + } +} + +function numIslands(grid) { + let numberOfIslands = 0; + + for (let row = 0; row < grid.length; row++) { + for (let col = 0; col < grid[row].length; col++) { + if (grid[row][col] === '1') { + numberOfIslands++; + grid[row][col] = 0; // marked as visited + + dfs(grid, row - 1, col); // top + dfs(grid, row + 1, col); // bottom + dfs(grid, row, col - 1); // left + dfs(grid, row, col + 1); // right + } + } + } + + return numberOfIslands; +}