-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8-numberOfIslands.py
84 lines (63 loc) · 1.98 KB
/
8-numberOfIslands.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
"""
Count the number of ilands in a 2 dimentional matrix
- An island is defined to a portion of land represented by 1
- Water is represented as 0
example:
[
[1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1],
[1,1,0,0,0,0,0,1,1],
[1,1,0,0,0,0,0,1,1],
[1,1,0,0,0,0,0,1,1],
[1,1,0,0,0,0,0,0,0],
]
result should be 1
"""
island_map = [
[1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1],
[1,1,0,0,0,0,0,1,1],
[1,1,0,0,0,0,0,1,1],
[1,1,0,0,0,0,0,1,1],
[1,1,0,0,0,0,0,0,0],
]
# result shoud be 1
def countHowManyIslands(matrix_map):
mutable_matrix_map = matrix_map
count = 0
def depthFirstSearch(i, j):
# Index out of bounds
if i < 0 or i > len(mutable_matrix_map) - 1:
return
if j < 0 or j > len(mutable_matrix_map[i]) - 1:
return
# Found the limit of the island, return
if mutable_matrix_map[i][j] == 0:
return
# Found land, change to 0 to not count twice
if mutable_matrix_map[i][j] == 1:
mutable_matrix_map[i][j] = 0
# Recursively search all sides (up, down, left, right)
depthFirstSearch(i + 1, j)
depthFirstSearch(i - 1, j)
depthFirstSearch(i, j + 1)
depthFirstSearch(i, j - 1)
# Return 1 to count as 1 island
return 1
# BEFORE
for i in range(0, len(mutable_matrix_map)):
for j in range(0, len(mutable_matrix_map[i])):
print(mutable_matrix_map[i][j], end="")
print("")
# PROCESS
for i in range(0, len(mutable_matrix_map)):
for j in range(0, len(mutable_matrix_map[i])):
if mutable_matrix_map[i][j] == 1:
count += depthFirstSearch(i, j)
# AFTER
#for i in range(0, len(mutable_matrix_map) - 1):
# for j in range(0, len(mutable_matrix_map[i]) - 1):
# print(mutable_matrix_map[i][j], end="")
# print("")
print("Number of islands = ", count)
countHowManyIslands(island_map)