forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 1
/
problem_084.py
40 lines (31 loc) · 964 Bytes
/
problem_084.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
def add_island(x, y, world_map, visited):
coord = "{}-{}".format(x, y)
if coord in visited:
return 0
visited.add(coord)
if x > 0 and world_map[x-1][y]:
add_island(x-1, y, world_map, visited)
if x < len(world_map) - 1 and world_map[x+1][y]:
add_island(x+1, y, world_map, visited)
if y > 0 and world_map[x][y-1]:
add_island(x, y-1, world_map, visited)
if y < len(world_map[0]) - 1 and world_map[x][y+1]:
add_island(x, y+1, world_map, visited)
return 1
def count_islands(world_map):
count = 0
visited = set()
for i in range(len(world_map)):
for k in range(len(world_map[0])):
if world_map[i][k]:
count += add_island(i, k, world_map, visited)
return count
world_map = [
[1, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 0, 1],
[1, 1, 0, 0, 1],
]
assert count_islands(world_map) == 4