PracticeNeetCode ↗LeetCode ↗
Given a 2D grid of "1" (land) and "0" (water), return the number of islands. An island is a group of land cells connected horizontally or vertically, surrounded by water.
"1" is found, increment the island count and flood-fill from it."1" as visited so it's never re-counted.Time: O(rows · cols) — Space: O(rows · cols)
from collections import deque
def numIslands(grid: list[list[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
visited = set()
islands = 0
def bfs(r: int, c: int) -> None:
queue = deque([(r, c)])
visited.add((r, c))
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" and (nr, nc) not in visited):
visited.add((nr, nc))
queue.append((nr, nc))
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r, c) not in visited:
islands += 1
bfs(r, c)
return islandsHow the solution above works, piece by piece.
visited remembers land cells already assigned to an island.bfs.bfs queues the start cell, then repeatedly pops a cell and queues each of its 4 neighbours that is land, inside the grid, and not yet visited.Running it on the example grid: