-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra.py
76 lines (64 loc) · 2.08 KB
/
Dijkstra.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
def dijkstra(graph, current, target, start="", visited=set(), dist=dict(), prev=dict()):
if not visited:
start = current
dist[current] = 0
if current == target:
return dist[target], get_path_dijkstra(prev, start, target, [])
for next in get_neighbours(graph, current):
if next not in visited:
dist_next = dist.get(next, float('inf'))
candidate_dist = dist[current] + graph[current][next]
if candidate_dist < dist_next:
dist[next] = candidate_dist
prev[next] = current
visited.add(current)
nexts = dict((node, dist.get(node, float('inf'))) for node in graph if node not in visited)
next = min(nexts, key=nexts.get)
if dist.get(next, float('inf')) == float('inf'):
return -1
return dijkstra(graph, next, target, start, visited, dist, prev)
def get_path_dijkstra(paths, start, current, path):
if current == start:
return [start] + path
return get_path_dijkstra(paths, start, paths[current], [current] + path)
def add_node(graph, node):
if node not in graph:
graph[node] = {}
def get_neighbours(graph, node):
nodes = []
if node in graph:
for neighbour in graph[node]:
if neighbour not in nodes:
nodes.append(neighbour)
return nodes
def edges_to_graph(edges):
graph = dict()
for edge in edges:
weight = edge.pop()
node1 = edge.pop()
if node1 not in graph:
add_node(graph, node1)
if edge:
node2 = edge.pop()
if node2 not in graph:
add_node(graph, node2)
else:
node2 = node1
graph[node2][node1] = weight
return graph
def to_string(graph):
res = "Graph :\n"
for k in graph:
res += str(k) + " : " + str(graph[k]) + "\n"
return res
E = [['A', 'B', 3],
['A', 'C', 5],
['B', 'C', 6],
['B', 'D', 7],
['C', 'D', 1],
['D', 'C', 2],
['E', 'F', 3],
['F', 'C', 5]]
H = edges_to_graph(E)
print(to_string(H))
print(dijkstra(H, 'A', 'D'))