forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount_islands.py
More file actions
65 lines (56 loc) · 1.45 KB
/
count_islands.py
File metadata and controls
65 lines (56 loc) · 1.45 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
59
60
61
62
63
64
65
"""
This is a bfs-version of counting-islands problem in dfs section.
Given a 2d grid map of '1's (land) and '0's (water),
count the number of islands.
An island is surrounded by water and is formed by
connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
Example 3:
111000
110000
100001
001101
001100
Answer: 3
Example 4:
110011
001100
000001
111100
Answer: 5
"""
def count_islands(grid):
row = len(grid)
col = len(grid[0])
num_islands = 0
visited = [[0] * col for i in range(row)]
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
queue = []
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.pop(0)
for k in range(len(directions)):
nx_x = x + directions[k][0]
nx_y = y + directions[k][1]
if nx_x >= 0 and nx_y >= 0 and nx_x < row and nx_y < col:
if 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