forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount_islands_bfs.py
More file actions
58 lines (45 loc) · 1.61 KB
/
count_islands_bfs.py
File metadata and controls
58 lines (45 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
Count Islands (BFS)
Given a 2D grid of 1s (land) and 0s (water), count the number of islands
using breadth-first search. An island is a group of adjacent lands
connected horizontally or vertically.
Reference: https://leetcode.com/problems/number-of-islands/
Complexity:
Time: O(M * N)
Space: O(M * N)
"""
from __future__ import annotations
from collections import deque
def count_islands(grid: list[list[int]]) -> int:
"""Return the number of islands in *grid*.
Args:
grid: 2D matrix of 0s and 1s.
Returns:
Number of connected components of 1s.
Examples:
>>> count_islands([[1, 0], [0, 1]])
2
"""
row = len(grid)
col = len(grid[0])
num_islands = 0
visited = [[0] * col for _ in range(row)]
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
queue: deque[tuple[int, int]] = deque()
for i in range(row):
for j, num in enumerate(grid[i]):
if num == 1 and visited[i][j] != 1:
visited[i][j] = 1
queue.append((i, j))
while queue:
x, y = queue.popleft()
for k in range(len(directions)):
nx_x = x + directions[k][0]
nx_y = y + directions[k][1]
if (0 <= nx_x < row and 0 <= nx_y < col
and visited[nx_x][nx_y] != 1
and grid[nx_x][nx_y] == 1):
queue.append((nx_x, nx_y))
visited[nx_x][nx_y] = 1
num_islands += 1
return num_islands