-
Notifications
You must be signed in to change notification settings - Fork 139
/
find_the_number_of_connected_components.py
50 lines (45 loc) · 1.14 KB
/
find_the_number_of_connected_components.py
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
''' Find the number of connected components '''
from collections import deque
n = 15
m = 14
data = [
'00000111100000',
'11111101111110',
'11011101101110',
'11011101100000',
'11011111111111',
'11011111111100',
'11000000011111',
'01111111111111',
'00000000011111',
'01111111111000',
'00011111111000',
'00000001111000',
'11111111110011',
'11100011111111',
'11100011111111'
]
visited = [[False] * m for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def bfs(x, y):
queue = deque([(x, y)])
visited[x][y] = True
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or ny < 0 or nx >= n or ny >= m:
continue
if data[x][y] == '0' and not visited[nx][ny]:
visited[nx][ny] = True
queue.append((nx, ny))
result = 0
for i in range(n):
for j in range(m):
# Find the number of connected components consisting only of '0'.
if data[i][j] == '0' and not visited[i][j]:
bfs(i, j)
result += 1
print(result)