added dijkstra.py file to utils
This commit is contained in:
parent
075ac738e4
commit
ff2c184c65
86
utils/dijkstra.py
Normal file
86
utils/dijkstra.py
Normal file
@ -0,0 +1,86 @@
|
||||
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))
|
@ -13,7 +13,7 @@ def clamp(mn, value, mx):
|
||||
|
||||
|
||||
def main():
|
||||
# 2024-06-27_21.01.45_Lycacraft_minecraft~overworld_day.png
|
||||
# utils/2024-06-27_21.01.45_Lycacraft_minecraft~overworld_day.png
|
||||
# 6144,10240
|
||||
input_path = input("Input image: ")
|
||||
output_path = input(f"Output dir (default: {DEFAULT_PATH}): ")
|
||||
|
Loading…
Reference in New Issue
Block a user