From df5248af9f7b31b6e23595426207f5cfd933b3aa Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 21 Jul 2026 05:02:59 -0600 Subject: [PATCH] adding updates --- .../round_1/23_number_of_islands.py | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/my_project/interviews/google_top_exercises/round_1/23_number_of_islands.py diff --git a/src/my_project/interviews/google_top_exercises/round_1/23_number_of_islands.py b/src/my_project/interviews/google_top_exercises/round_1/23_number_of_islands.py new file mode 100644 index 00000000..9f7f4b64 --- /dev/null +++ b/src/my_project/interviews/google_top_exercises/round_1/23_number_of_islands.py @@ -0,0 +1,65 @@ +from typing import List +from collections import deque + + +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + """BFS approach - explores island level by level""" + + if not grid: + return 0 + + rows, cols = len(grid), len(grid[0]) + islands = 0 + + def bfs(r: int, c: int): + queue = deque([(r,c)]) + grid[r][c] = '0' + + while queue: + row, col = queue.popleft() + + for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]: + nr, nc = row + dr, col + dc + if (0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == '1'): + grid[nr][nc] = '0' + queue.append((nr,nc)) + + for r in range(rows): + for c in range(cols): + if grid[r][c] == '1': + islands += 1 + bfs(r,c) + + return islands + + + + + def numIslands_DFS(grid: List[List[str]]) -> int: + """DFS approach - explores island depth-first""" + + if not grid: + return 0 + + rows, cols = len(grid), len(grid[0]) + islands = 0 + + def dfs(r: int, c: int): + if (r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == '0'): + return + + grid[r][c] = '0' + + dfs(r-1,c) + dfs(r+1,c) + dfs(r,c-1) + dfs(r,c+1) + + for r in range(rows): + for c in range(cols): + if grid[r][c] == '1': + islands += 1 + dfs(r,c) + + return islands \ No newline at end of file