86 lines
2.0 KiB
Python
86 lines
2.0 KiB
Python
from math import inf
|
|
|
|
class Edge:
|
|
|
|
length = 0
|
|
|
|
def __init__(self, start, end, length):
|
|
self.length = length
|
|
self.start = start
|
|
self.end = end
|
|
|
|
class Node:
|
|
|
|
def __init__(self, xpos, ypos):
|
|
self.xpos = xpos
|
|
self.ypos = ypos
|
|
|
|
class Graph:
|
|
|
|
def __init__(self):
|
|
self.edges = list()
|
|
self.nodes = list()
|
|
|
|
def add_node(self, xpos, ypos):
|
|
self.nodes.append(Node(xpos, ypos))
|
|
|
|
def add_edge(self, start_index, end_index, length):
|
|
self.edges.append(Edge(start_index, end_index, length))
|
|
|
|
|
|
def Dijkstra(graph, source_index, target_index):
|
|
|
|
n = len(graph.nodes)
|
|
|
|
if (target_index >= n):
|
|
return None
|
|
|
|
unvisited = list(range(n))
|
|
|
|
distances_from_start = [inf] * n
|
|
distances_from_start[source_index] = 0
|
|
|
|
node_sequences = [list() for i in range(n)]
|
|
node_sequences[source_index] = [source_index]
|
|
|
|
while(True):
|
|
try:
|
|
current_index = min(unvisited, key = lambda i: distances_from_start[i])
|
|
except ValueError:
|
|
break
|
|
|
|
if current_index == target_index:
|
|
break
|
|
|
|
unvisited.remove(current_index)
|
|
|
|
for edge in filter(
|
|
lambda e: e.start == current_index or e.end == current_index,
|
|
graph.edges):
|
|
|
|
start = current_index
|
|
end = edge.end if edge.start == current_index else edge.start
|
|
|
|
if end in unvisited and distances_from_start[end] > distances_from_start[start] + edge.length:
|
|
distances_from_start[end] = distances_from_start[start] + edge.length
|
|
node_sequences[end] = node_sequences[start].copy()
|
|
node_sequences[end].append(end)
|
|
|
|
return node_sequences[target_index]
|
|
|
|
|
|
graph = Graph()
|
|
|
|
graph.add_node(1, 2)
|
|
graph.add_node(4, 7)
|
|
graph.add_node(3,1)
|
|
graph.add_node(-2,0)
|
|
graph.add_node(0,0)
|
|
|
|
graph.add_edge(0, 1, 1)
|
|
graph.add_edge(1, 2, 2)
|
|
graph.add_edge(2, 3, 3)
|
|
graph.add_edge(3, 0, 1)
|
|
graph.add_edge(1, 3, 3)
|
|
|
|
print(Dijkstra(graph, 0, 5)) |