-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.py
28 lines (26 loc) · 876 Bytes
/
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
import networkx as nx
import heapq as hq
def dijkstra(graph: nx.DiGraph, start_node: str):
costs = {}
for node in graph.nodes:
if node == start_node:
continue
elif graph.has_edge(start_node, node):
costs[node] = graph.edges[start_node, node]["weight"]
else:
costs[node] = float("inf")
heap = []
for node, cost in costs.items():
hq.heappush(heap, (cost, node))
while len(heap) != 0:
node = hq.heappop(heap)
for neighbor in graph.neighbors(node[1]):
if (
costs[node[1]] + graph.edges[node[1], neighbor]["weight"]
< costs[neighbor]
):
costs[neighbor] = (
costs[node[1]] + graph.edges[node[1], neighbor]["weight"]
)
hq.heapify(heap)
return costs