-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.py
86 lines (69 loc) · 2.33 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
77
78
79
80
81
82
83
84
85
86
from collections import defaultdict
# Initializing the Graph Class
class Graph:
def __init__(self):
self.nodes = set()
self.edges = defaultdict(list)
self.distances = {}
def addNode(self, value):
self.nodes.add(value)
def addEdge(self, fromNode, toNode, distance):
if toNode in self.nodes:
self.edges[fromNode].append(toNode)
self.distances[(fromNode, toNode)] = distance
else:
pass
# Implementing Dijkstra's Algorithm
def dijkstra(graph, initial):
visited = {initial: 0}
path = defaultdict(list)
nodes = set(graph.nodes)
while nodes:
minNode = None
for node in nodes:
if node in visited:
if minNode is None:
minNode = node
elif visited[node] < visited[minNode]:
minNode = node
if minNode is None:
break
nodes.remove(minNode)
currentWeight = visited[minNode]
for edge in graph.edges[minNode]:
weight = currentWeight + graph.distances[(minNode, edge)]
if edge not in visited or weight < visited[edge]:
visited[edge] = weight
path[edge].append(minNode)
return visited, path
def find_path(path, begin, end):
path_lst = [end]
calculating = True
while calculating:
previous = path[end][0]
path_lst.append(previous)
if previous == begin:
calculating = False
else:
end = previous
return path_lst[::-1]
def create_graph_from_matrix(size, matrix):
G = Graph()
for i in range(len(matrix)):
G.addNode(i)
hlist_right = []
hlist_left = []
for i in range(size):
hlist_right.append(size * (i + 1) - 1)
hlist_left.append(size * (i + 1))
for i in range(len(matrix)):
if not matrix[i]:
if i + 1 in G.nodes and not matrix[i + 1] and i not in hlist_right:
G.addEdge(i, i + 1, 1)
if i - 1 in G.nodes and not matrix[i - 1] and i not in hlist_left:
G.addEdge(i, i - 1, 1)
if i + size in G.nodes and not matrix[i + size]:
G.addEdge(i, i + size, 1)
if i - size in G.nodes and not matrix[i - size]:
G.addEdge(i, i - size, 1)
return G