-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find the number of islands.py
63 lines (50 loc) · 1.56 KB
/
Find the number of islands.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
51
52
53
54
55
56
57
58
59
60
61
62
63
from collections import deque
class Solution:
def numIslands(self, grid):
rows, cols = len(grid), len(grid[0])
visited = set()
islands = 0
def bfs(row, col):
q = deque()
q.append((row, col))
visited.add((row, col))
directions = (
(0, 1),
(1, 0),
(0, -1),
(-1, 0),
(1, 1),
(1, -1),
(-1, -1),
(-1, 1),
)
while q:
r, c = q.popleft()
for dr, dc in directions:
nr, nc = dr + r, dc + c
if (
nr in range(rows)
and nc in range(cols)
and grid[nr][nc] == 1
and (nr, nc) not in visited
):
visited.add((nr, nc))
q.append((nr, nc))
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1 and (i, j) not in visited:
bfs(i, j)
islands += 1
return islands
if __name__ == "__main__":
grid = [
[1, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 0, 0, 1],
[1, 1, 1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 1, 0, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 0, 0, 1, 0, 0],
]
obj = Solution()
print(obj.numIslands(grid))