-
Notifications
You must be signed in to change notification settings - Fork 3
/
84_Amazon_Find_Islands_From_Matrix.py
executable file
·93 lines (70 loc) · 1.92 KB
/
84_Amazon_Find_Islands_From_Matrix.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""
This problem was asked by Amazon.
Given a matrix of 1s and 0s, return the number of "islands" in the matrix.
A 1 represents land and 0 represents water, so an island is a group of 1s
that are neighboring whose perimeter is surrounded by water.
For example, this matrix has 4 islands.
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
"""
moves = [
# row, col
(0, 1), # west
(0, -1), # east
(1, 0), # south
(-1, 0), # north
(1,1), # south-west
(1, -1), # south-east
(-1, 1), # north-west
(-1, -1) # north-east
]
def mark_island(row, col, land_map, marker):
if row < 0 or col<0 or row>=len(land_map) or col >= len(land_map[0]):
return land_map
if land_map[row][col]== 0:
return land_map
if land_map[row][col]== marker:
return land_map
if land_map[row][col] == 1:
land_map[row][col] = marker
for r,c in moves:
land_map = mark_island(row+r, col+c, land_map, marker)
return land_map
def find_num_of_islands(land_map):
islands_found = 0
for i in range(len(land_map)):
for j in range(len(land_map[0])):
if land_map[i][j] == 1:
islands_found+= 1
land_map = mark_island(i, j, land_map, marker='i')
# print(*land_map, sep='\n')
return islands_found
if __name__ == '__main__':
land_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],
]
print(find_num_of_islands(land_map)) # 4
land_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],
[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],
]
print(find_num_of_islands(land_map)) # 7