forked from bloominstituteoftechnology/Graphs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday3.py
87 lines (68 loc) · 2.46 KB
/
day3.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
#each number is a node
#edges are up, down, left and right except for the edges of the graph
islands = [[0, 1, 0, 1, 0],
[1, 1, 0, 1, 1],
[0, 0, 1, 0, 0],
[1, 0, 1, 0, 0],
[1, 1, 0, 0, 0]]
islands_2 = [[1, 0, 0, 1, 1, 0, 1, 1, 0, 1],
[0, 0, 1, 1, 0, 1, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1, 0, 0, 1, 1],
[0, 0, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 1, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 1, 0, 0, 0],
[1, 0, 1, 1, 0, 0, 0, 1, 1, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 1, 0, 0, 1, 0]]
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
def island_counter(islands):
counter = 0
visited = set()
def get_neighbors(coords):
row, col = coords
neighbors = []
if row > 0 and islands[row-1][col] == 1:
neighbors.append((row-1, col))
if row < len(islands) - 1 and islands[row+1][col] == 1:
neighbors.append((row+1, col))
if col > 0 and islands[row][col-1] == 1:
neighbors.append((row, col-1))
if col < len(islands[row]) -1 and islands[row][col+1] == 1:
neighbors.append((row, col+1))
return neighbors
def bft(row, col):
q = Queue()
q.enqueue((row, col))
while q.size() > 0:
coords = q.dequeue()
if coords not in visited:
visited.add(coords)
for neighbor in get_neighbors(coords):
q.enqueue(neighbor)
#for all nodes in the graph
for row in range(len(islands)):
for col in range(len(islands[row])):
node_val = islands[row][col]
island = (row, col)
#if find an unvisited 1 node
if island not in visited and node_val == 1:
#BFT from that node
bft(row, col)
#increment the counter
counter += 1
#return counter
return counter
print(island_counter(islands)) # returns 4
print(island_counter(islands_2)) #returns 13