From c4d98c4064958a2221da8f2d3e35e82d66ee2e42 Mon Sep 17 00:00:00 2001 From: jaygala Date: Wed, 5 Oct 2022 14:29:07 +0530 Subject: [PATCH] added code for number of islands --- LeetCode/Practice/number-of-islands.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 LeetCode/Practice/number-of-islands.py diff --git a/LeetCode/Practice/number-of-islands.py b/LeetCode/Practice/number-of-islands.py new file mode 100644 index 00000000..a411efda --- /dev/null +++ b/LeetCode/Practice/number-of-islands.py @@ -0,0 +1,23 @@ +class Solution: + def numIslands(self, grid: list[list[str]]) -> int: + def dfs(row, col, grid): + + if row < 0 or col < 0 or row >= len(grid) or \ + col >= len(grid[0]) or grid[row][col] != '1': + return + + #mark as visited + grid[row][col] = 'visited' + + for dx, dy in [(-1,0),(1,0),(0,1),(0,-1)]: + dfs(row + dx, col + dy, grid) + + ans = 0 + + for row in range(len(grid)): + for col in range(len(grid[0])): + if grid[row][col] == '1': + dfs(row, col, grid) + ans += 1 + return ans + \ No newline at end of file