-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.py
More file actions
54 lines (42 loc) · 1.64 KB
/
Graph.py
File metadata and controls
54 lines (42 loc) · 1.64 KB
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
import math
class Graph:
vertices = list()
def search(self, start, goal):
for node in self.vertices:
if node == start:
node.cost = 0
else:
node.cost = math.inf
visited = list()
path = list()
updated = list()
path = self.dijikstra_search(start, goal, start, visited, path, updated)
return path
def dijikstra_search(self, start, goal, current, visited, path, updated):
if visited is None:
visited = list()
visited.append(current)
path.append('{}{}'.format(current, current.cost))
if current == goal:
print("The path to {} using Dijikstra's algorithm is: {}".format(goal, path))
return path
else:
# evaluate cost of unvisited connected nodes & determine the next node to visit
next = None
for child in current.children:
cost = current.cost + child.path_cost
if cost < child.child.cost:
child.child.cost = cost
updated.append(child.child)
for n in updated: #current.children:
if n not in visited:
if next is None:
next = n
else:
if n not in visited:
if n.cost < next.cost:
next = n
if next is not None:
return self.dijikstra_search(start, goal, next, visited, path, updated)
else:
print('The path to {} could not be found'.format(goal))