dijkstra: add simple dijkstra
This commit is contained in:
33
dijsktra.py
33
dijsktra.py
@@ -4,16 +4,45 @@ This module holds the logic for the solving
|
||||
|
||||
|
||||
class Dijkstra():
|
||||
def __init__(self, graph: dict):
|
||||
def __init__(self, graph: dict, connection: tuple):
|
||||
"""
|
||||
table: matrix with vertex as key, price and prev vertex as value
|
||||
OL: open list, to keep track of finished vertecis
|
||||
"""
|
||||
self.graph = graph
|
||||
self.table = {}
|
||||
self.OL = []
|
||||
for vertex in graph:
|
||||
self.table.update({vertex: {"distance": 9999999, "prev": None}})
|
||||
self.table[connection[0]]["distance"] = 0
|
||||
|
||||
def algorithm(self):
|
||||
print("Performing Dijkstra on the following graph...")
|
||||
for vertex in self.graph:
|
||||
print(f"{vertex}: {self.graph[vertex]}")
|
||||
|
||||
for v1 in self.graph.keys():
|
||||
neighbors = self.graph[v1]
|
||||
for n in neighbors:
|
||||
key = [elem for elem in n.keys()][0] # name of neighbor node
|
||||
# NOTE: change time or co2 here
|
||||
edge = n[key]["time"]
|
||||
dist = self.table[v1]["distance"] + edge
|
||||
if dist < self.table[key]["distance"]:
|
||||
self.table[key]["distance"] = dist
|
||||
self.table[key]["prev"] = v1
|
||||
|
||||
print("self.table:", self.table)
|
||||
|
||||
def print_result(self, connection: tuple):
|
||||
sequence = []
|
||||
(start, dest) = connection
|
||||
# start at destination
|
||||
sequence.append(dest)
|
||||
|
||||
while start not in sequence:
|
||||
# previous jump
|
||||
prev = self.table[sequence[-1]]["prev"]
|
||||
sequence.append(prev)
|
||||
|
||||
sequence.reverse()
|
||||
print(sequence)
|
||||
|
||||
Reference in New Issue
Block a user