-
Notifications
You must be signed in to change notification settings - Fork 19
/
4.1-Route_Between_Nodes.py
128 lines (97 loc) · 2.77 KB
/
4.1-Route_Between_Nodes.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# CTCI 4.1
# Route Between Nodes
import unittest
class Graph():
def __init__(self):
self.max_vertices = 6
self.vertices = [0] * self.max_vertices
self.count = 0
def addNode(self, x):
if self.count < self.max_vertices:
self.vertices[self.count] = x
self.count += 1
else:
print ("Graph full")
def getNodes(self):
return self.vertices
class Node():
def __init__(self, vertex, adjacentLength):
self.adjacent = [0] * adjacentLength
self.vertex = vertex
self.adjacentCount = 0
self.visited = False
def addAdjacent(self, x):
if self.adjacentCount < len(self.adjacent):
self.adjacent[self.adjacentCount] = x
self.adjacentCount += 1
else:
print ("No more adjacent nodes can be added")
def getAdjacent(self):
return self.adjacent
def getVertex(self):
return self.vertex
### My BFS
def route(g, start, end):
if start == end:
return True
visited = [False]*(g.count)
queue = []
queue.append(start)
#visited[start] = True
start.visited = True
while queue:
v = queue.pop(0)
if v == end:
return True
for n in v.getAdjacent():
if n.visited == False:
queue.append(n)
n.visited = True
return False
#-------------------------------------------------------------------------------
# CTCI Solution
#-------------------------------------------------------------------------------
#Testing
def createNewGraph():
g = Graph()
sizegraph = 6
temp = [0] * sizegraph
temp[0] = Node("a", 3)
temp[1] = Node("b", 0)
temp[2] = Node("c", 0)
temp[3] = Node("d", 1)
temp[4] = Node("e", 1)
temp[5] = Node("f", 0)
temp[0].addAdjacent(temp[1])
temp[0].addAdjacent(temp[2])
temp[0].addAdjacent(temp[3])
temp[3].addAdjacent(temp[4])
temp[4].addAdjacent(temp[5])
for i in range(sizegraph):
g.addNode(temp[i])
return g
def createNewGraphWithLoop():
g = Graph()
sizegraph = 6
temp = [0] * sizegraph
temp[0] = Node("a", 1)
temp[1] = Node("b", 1)
temp[2] = Node("c", 1)
temp[3] = Node("d", 1)
temp[4] = Node("e", 2)
temp[5] = Node("f", 0)
temp[0].addAdjacent(temp[1])
temp[1].addAdjacent(temp[2])
temp[2].addAdjacent(temp[3])
temp[3].addAdjacent(temp[4])
temp[4].addAdjacent(temp[1])
temp[4].addAdjacent(temp[5])
for i in range(sizegraph):
g.addNode(temp[i])
return g
g = createNewGraphWithLoop()
n = g.getNodes()
start = n[0]
end = n[5]
print ("Start at:", start.getVertex(), "End at: ", end.getVertex())
print (route(g, start, end))