Intuition
Scan the grid. Every fresh '1' you land on is an island — start there and
flood-fill outwards, marking every connected land cell visited so you don't
count the same island twice.
Explanation
Approach
- For each cell
(r, c):- If
grid[r][c] == '1', increment count and DFS from(r, c).
- If
- DFS sets
grid[r][c] = '0'(or uses a visited set) and recurses into the four neighbors.
Implementation
from collections import deque
def numIslands(grid):
if not grid:
return 0
m, n = len(grid), len(grid[0])
visited = set()
count = 0
for r in range(m):
for c in range(n):
if grid[r][c] == '1' and (r, c) not in visited:
count += 1
queue = deque([(r, c)])
visited.add((r, c))
while queue:
i, j = queue.popleft()
for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
ni, nj = i + di, j + dj
if 0 <= ni < m and 0 <= nj < n and grid[ni][nj] == '1' and (ni, nj) not in visited:
visited.add((ni, nj))
queue.append((ni, nj))
return count