-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithms.py
355 lines (285 loc) · 10.6 KB
/
algorithms.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import math
from classes import Config, Tile
####################### Breadth First Search #######################
class BFS:
def __init__(self, Adj, source, target):
self.Adj = Adj
self.source = source
self.target = target
self.targetFound = False
self.parent = {source:None} # parent of source is None
self.nodeToLevelDict = {source:0} # level of source is 0
# each element of the list represents a level and has a list with all nodes belonging to that level (frontier)
# e.g. level 0 has list of elements [source]
self.frontierList = [[source]]
def search(self):
i = 1
frontier = [self.source] # starting frontier is source
while frontier:
next = []
for u in frontier:
for v in self.Adj[u]:
# if not already explored
if v not in self.nodeToLevelDict:
self.nodeToLevelDict[v] = i
self.parent[v] = u
next.append(v)
# check if target found
if v == self.target:
self.targetFound = True
self.frontierList.append(next)
return self.find_path(), self.nodeToLevelDict, self.frontierList
frontier = next
self.frontierList.append(frontier)
i = i+1 # increment i
return None, self.nodeToLevelDict, self.frontierList
def find_path(self):
shortest_path = [self.target] # inverted path, starting from target back to source
next_parent = self.parent[self.target]
while True:
if next_parent:
shortest_path.append(next_parent)
next_parent = self.parent[next_parent]
else:
return list(reversed(shortest_path)) # reverse list, from source to target
####################### Depth First Search #######################
class DFS:
def __init__(self, Adj, source, target=None):
self.Adj = Adj
self.source = source
self.target = target
self.parent = {source:None}
self.targetFound = False
self.exploredTiles = [self.source]
self.nodeToLevelDict = {source:0} # level of source is 0
self.frontierList = [[source]] # frontier list (for DFS frontier has only 1 node but it is still a list)
self.currentLevel = 1
def search(self):
self.DFS_visit(self.source)
return self.find_path(), self.nodeToLevelDict, self.frontierList
# Recursive part of DFS
def DFS_visit(self, s):
for v in self.Adj[s]:
if v not in self.parent:
if self.targetFound:
return
self.exploredTiles.append(v) # append to explored tiles
self.nodeToLevelDict[v] = self.currentLevel
self.frontierList.append([v])
self.currentLevel += 1
# check if target found
if v == self.target:
self.targetFound = True
self.parent[v] = s
self.DFS_visit(v)
def find_path(self):
if not self.targetFound:
return None
path = [self.target] # inverted path, starting from target back to source
next_parent = self.parent[self.target]
while True:
if next_parent:
path.append(next_parent)
next_parent = self.parent[next_parent]
else:
return list(reversed(path)) # reverse list, from source to target
####################### Dijkstra #######################
# optimal but non efficient
class Dijkstra: # if target!=None it is Uniform cost search
def __init__(self, Adj, W, source, target=None):
self.Adj = Adj
self.W = W
self.source = source
self.target = target
self.targetFound = False
N = len(Adj.keys()) # number of nodes
self.levelToIdList = [[source]] # to show exploration
self.levelToCostList = [0] # to draw cost when showing exploration
self.visitedList = [source] # visited nodes that are expanded
self.exploredList = [source] # visited means the algorithm looked at it, not necessarily expanded
# initialize dictionaries
self.distDict = {} # maps id to g(n)
self.parentDict = {}
for node in Adj.keys():
self.distDict[node] = math.inf
self.parentDict[node] = None
self.distDict[source] = 0
self.pq = {} # priority queue
def search(self):
level = 0
self.pq[self.source] = 0
while len(self.pq) > 0:
index = poll(self.pq)
self.visitedList.append(index)
level += 1
if index == self.target: # if the target is visited, interrupt search because min dist has been found
self.targetFound = True
break
newDist = self.distDict[index] + self.W[index] # which is self.distDict[edge]
for edge in self.Adj[index]:
if edge not in self.visitedList and edge not in self.pq.keys(): # not visited and not in pq
self.exploredList.append(edge)
elif edge in self.pq.keys() and newDist < self.pq[edge]:
pass
else: # edge in frontier but worse distance
continue
self.levelToIdList.append([edge]) # to show relaxation
self.levelToCostList.append(newDist) # to show relaxation
self.distDict[edge] = newDist
self.parentDict[edge] = index
self.pq[edge] = newDist
return self.find_path(), self.distDict, self.levelToIdList, self.exploredList, self.levelToCostList
def find_path(self):
if not self.targetFound:
return None
shortest_path = [self.target] # inverted path, starting from target back to source
next_parent = self.parentDict[self.target]
while True:
if next_parent:
shortest_path.append(next_parent)
next_parent = self.parentDict[next_parent]
else:
return list(reversed(shortest_path)) # reverse list, from source to target
####################### Best-First Search #######################
# non optimal but often efficient
class B_FS:
def __init__(self, Adj, W, source, target):
if target == None:
return
self.Adj = Adj
self.W = W
self.source = source
self.target = target
self.targetFound = False
N = len(Adj.keys()) # number of nodes
self.levelToIdList = [[source]] # to show exploration
self.levelToCostList = [0] # to draw cost when showing exploration
self.visitedList = [source] # visited nodes that are expanded
self.exploredList = [source] # visited means the algorithm looked at it, not necessarily expanded
# initialize dictionaries
self.distDict = {} # maps id to g(n)
self.parentDict = {}
self.h = {} # heuristic function h(n)
for node in Adj.keys():
self.distDict[node] = math.inf
self.parentDict[node] = None
self.h[node] = compute_h(node, target)
self.distDict[source] = 0
self.pq = {} # priority queue
def search(self):
level = 0
self.pq[self.source] = self.h[self.source]
while len(self.pq) > 0:
index = poll(self.pq)
self.visitedList.append(index)
level += 1
if index == self.target: # if the target is visited, interrupt search because min dist has been found
self.targetFound = True
break
newDist = self.distDict[index] + self.W[index] # which is self.distDict[edge]
for edge in self.Adj[index]:
if edge not in self.visitedList and edge not in self.pq.keys():
self.exploredList.append(edge)
elif edge in self.pq.keys() and self.pq[edge] > newDist:
pass
else:
continue
self.levelToIdList.append([edge]) # to show relaxation
self.levelToCostList.append(newDist) # to show relaxation
self.distDict[edge] = newDist
self.parentDict[edge] = index
self.pq[edge] = self.h[edge]
return self.find_path(), self.distDict, self.levelToIdList, self.exploredList, self.levelToCostList
def find_path(self):
if not self.targetFound:
return None
shortest_path = [self.target] # inverted path, starting from target back to source
next_parent = self.parentDict[self.target]
while True:
if next_parent:
shortest_path.append(next_parent)
next_parent = self.parentDict[next_parent]
else:
return list(reversed(shortest_path)) # reverse list, from source to target
####################### A* #######################
class A_star:
def __init__(self, Adj, W, source, target):
if target == None:
return
self.Adj = Adj
self.W = W
self.source = source
self.target = target
self.targetFound = False
N = len(Adj.keys()) # number of nodes
self.levelToIdList = [[source]] # to show exploration
self.levelToCostList = [0] # to draw cost when showing exploration
self.visitedList = [source] # visited nodes that are expanded
self.exploredList = [source] # visited means the algorithm looked at it, not necessarily expanded
# initialize dictionaries
self.distDict = {} # maps id to g(n)
self.parentDict = {}
self.h = {} # heuristic function h(n)
for node in Adj.keys():
self.distDict[node] = math.inf
self.parentDict[node] = None
self.h[node] = compute_h(node, target)
self.distDict[source] = 0
self.pq = {} # priority queue
def search(self):
# print("\n\n### A* starting search")
level = 0
self.pq[self.source] = 0 + self.h[self.source] # (n, f = g + h)
while len(self.pq) > 0:
index = poll(self.pq)
self.visitedList.append(index)
# print("visiting node %s" % index)
level += 1
if index == self.target: # if the target is visited, interrupt search because min dist has been found
self.targetFound = True
break
for edge in self.Adj[index]:
new_f = self.distDict[index] + self.W[index] + self.h[edge]
newDist = self.distDict[index] + self.W[index]
# print("\n\tlooking at node %s" % edge)
if (edge not in self.visitedList) and (edge not in self.pq.keys()):
# print("\tnode %s is not visited or in queue. g = %f, h = %f, f = %f" % (edge, newDist, self.h[edge], new_f))
self.exploredList.append(edge)
self.levelToIdList.append([edge]) # to show relaxation
self.levelToCostList.append(newDist) # to show relaxation
self.distDict[edge] = newDist
self.parentDict[edge] = index
self.pq[edge] = newDist + self.h[edge]
elif (edge in self.pq.keys()) and (new_f < self.pq[edge]):
self.levelToIdList.append([edge]) # to show relaxation
self.levelToCostList.append(newDist) # to show relaxation
self.distDict[edge] = newDist
self.parentDict[edge] = index
self.pq[edge] = newDist + self.h[edge]
return self.find_path(), self.distDict, self.levelToIdList, self.exploredList, self.levelToCostList
def find_path(self):
if not self.targetFound:
return None
shortest_path = [self.target] # inverted path, starting from target back to source
next_parent = self.parentDict[self.target]
while True:
if next_parent:
shortest_path.append(next_parent)
next_parent = self.parentDict[next_parent]
else:
return list(reversed(shortest_path)) # reverse list, from source to target
####################### Util #######################
def poll(dic):
min = math.inf
next_node = None
for node in dic.keys():
if dic[node] <= min:
next_node = node
min = dic[node]
del dic[next_node]
return next_node
def compute_h(tile1, tile2): # compute h
tile1Pos = Tile.idToCoordDict[tile1]
tile2Pos = Tile.idToCoordDict[tile2]
# Manhattan distance
return (abs(tile1Pos[0]-tile2Pos[0]) + abs(tile1Pos[1]-tile2Pos[1])) / Config.TILE_SIZE