Loading…
Loading…
Given a grid of 1s (land) and 0s (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically.
Input (3 rows):
11 1 0 0
21 1 0 0
30 0 1 0Output: 2
Scan every cell; whenever you find an unvisited 1, that's a new island — run DFS (or BFS) from it to mark every connected 1 as visited, then increment the island count.
1def num_islands(grid):
2 rows, cols = len(grid), len(grid[0])
3 visited = set()
4 count = 0
5 def dfs(r, c):
6 if (r, c) in visited or not (0 <= r < rows and 0 <= c < cols) or grid[r][c] == 0:
7 return
8 visited.add((r, c))
9 for dr, dc in [(-1,0),(1,0),(0,-1),(0,1)]:
10 dfs(r + dr, c + dc)
11 for r in range(rows):
12 for c in range(cols):
13 if grid[r][c] == 1 and (r, c) not in visited:
14 dfs(r, c)
15 count += 1
16 return countLine 1: number of rows R Next R lines: space-separated grid row (0s and 1s)
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.