-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSC162_LAB17_SBK.py
258 lines (205 loc) · 7.29 KB
/
CSC162_LAB17_SBK.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# sarah kingan
# CSC162, summer2015
# Lab 17
#
# Using breadth first search revise the maze program from
# the recursion chapter to find the shortest path out of
# a maze.
#
# some code modified from Problem Solving with Algorithms
# and Data Structures, By Brad Miller and David Ranum
#
# http://www.codeskulptor.org/#user40_2vfgiICF7Y_18.py
#
#
class WeightedBinHeap:
def __init__(self):
self.heapList = [{'key': 'head','weight':'None'}]
self.currentSize = 0
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i]['weight'] < self.heapList[i//2]['weight']:
tmp = self.heapList[i//2]
self.heapList[i//2] = self.heapList[i]
self.heapList[i] = tmp
i = i // 2
def insert(self,key,weight):
d = {'key':key,'weight':weight}
self.heapList.append(d)
self.currentSize = self.currentSize + 1
self.percUp(self.currentSize)
def minChild(self,i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i*2]['weight'] < self.heapList[i*2+1]['weight']:
return i * 2
else:
return i * 2 + 1
def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i]['weight'] > self.heapList[mc]['weight']:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc
def delMin(self):
retNode = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapList.pop()
self.percDown(1)
return retNode
def buildHeap(self,list):
i = len(list) // 2
self.currentSize = len(list)
new = WeightedBinHeap().heapList
self.heapList = new + list
while (i > 0):
self.percDown(i)
i = i - 1
###############################################
class PriorityQueue:
def __init__(self):
self.wbh = WeightedBinHeap()
def enqueue(self,key,weight):
self.wbh.insert(key,weight)
def dequeue(self):
return self.wbh.delMin()
def isEmpty(self):
return self.wbh.currentSize == 0
def decreaseKey(self,key,weight):
i = 1
while i < (self.currentSize() + 1):
if self.wbh.heapList[i]['key'] == key:
self.wbh.heapList[i]['weight'] = weight
self.wbh.percUp(i)
else:
i = i + 1
def loadPriorityQueue(self,list):
self.wbh.buildHeap(list)
def currentSize(self):
return self.wbh.currentSize
###############################################
class Vertex:
def __init__(self,key):
self.id = key
self.connectedTo = {}
self.distance = float("inf")
self.pred = None
def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight
def __str__(self):
return str(self.id)
# return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])
def getConnections(self):
return self.connectedTo.keys()
def getId(self):
return self.id
def getWeight(self,nbr):
return self.connectedTo[nbr]
def setDistance(self,distance):
self.distance = distance
def getDistance(self):
return self.distance
def setPred(self,node):
self.pred = node
def getPred(self):
return self.pred
###############################################
class Graph:
def __init__(self):
self.vertList = {}
self.numVertices = 0
def addVertex(self,key):
self.numVertices = self.numVertices + 1
newVertex = Vertex(key)
self.vertList[key] = newVertex
return newVertex
def getVertex(self,n):
if n in self.vertList:
return self.vertList[n]
else:
return None
def __contains__(self,n):
return n in self.vertList
def addEdge(self,f,t,cost=0):
if f not in self.vertList:
nv = self.addVertex(f)
if t not in self.vertList:
nv = self.addVertex(t)
self.vertList[f].addNeighbor(self.vertList[t], cost)
def getVertices(self):
return self.vertList.keys()
def __iter__(self):
return (x for x in self.vertList.values())
###############################################
def maze2graph(mazeArray):
height = len(mazeArray)
width = len(mazeArray[0])
nodes = height * width
graph = Graph()
# iterate across each row starting at top left
for row in range(height):
for col in range(width):
position = col + row * width
# add each vertex, id consecutive number starting at top left
graph.addVertex(position)
# add edges at adjacent nodes that are spaces
if mazeArray[row][col] == ' ':
if mazeArray[row-1][col] == ' ':
graph.addEdge(position, position-width,1)
graph.addEdge(position-width, position,1)
if mazeArray[row][col-1] == ' ':
graph.addEdge(position, position-1,1)
graph.addEdge(position-1, position,1)
return graph
def graph2KeyWeightList(self):
l = []
for k in self.getVertices():
d = {}
d['key'] = k
d['weight'] = self.getVertex(k).getDistance()
l.append(d)
return l
def dijkstra(graph,start):
startVertex = graph.getVertex(start)
startVertex.setDistance(0)
pq = PriorityQueue()
keyDistList = graph2KeyWeightList(graph)
pq.loadPriorityQueue(keyDistList)
i = start
while i < (pq.currentSize() + 1):
key = pq.dequeue()['key']
currentVert = graph.getVertex(key)
print ("current vertex is ", key)
for nextVert in currentVert.getConnections():
print nextVert
print currentVert.getDistance()
print nextVert.getDistance()
print currentVert.getWeight(nextVert)
newDist = currentVert.getDistance() + currentVert.getWeight(nextVert)
print newDist
if newDist < nextVert.getDistance():
print "update distance"
nextVert.setDistance( newDist )
print nextVert.getDistance()
nextVert.setPred(currentVert)
print nextVert.getPred()
# this next step is not working! I can get the node with the reduced weight
# to swap with its parent but the rest of the heap is not reordered.
pq.decreaseKey(nextVert,newDist)
i = i + 1
# print final list of vertices and distance
# to get path through maze list vertices by increasing distance
for v in graph:
print("%s, %s" % (v, v.getDistance()))
maze = [['+' for i in range(7)], [' ',' ','+',' ',' ',' ','+'], \
['+',' ','+',' ','+','+','+'], ['+',' ',' ',' ','+',' ','+'], \
['+',' ','+',' ',' ',' ',' '], ['+' for i in range(7)]]
# print my maze
for i in range(len(maze)):
print ' '.join(maze[i])
g = maze2graph(maze)
dijkstra(g,7)