upd
This commit is contained in:
26
algorithms/labs/lab7/code/3.py
Normal file
26
algorithms/labs/lab7/code/3.py
Normal file
@@ -0,0 +1,26 @@
|
||||
import heapq
|
||||
|
||||
|
||||
def dijkstra(graph, start):
|
||||
dist = {v: float("inf") for v in graph}
|
||||
dist[start] = 0
|
||||
pq = [(0, start)]
|
||||
while pq:
|
||||
d, v = heapq.heappop(pq)
|
||||
if d > dist[v]:
|
||||
continue
|
||||
for u, w in graph[v]:
|
||||
if dist[v] + w < dist[u]:
|
||||
dist[u] = dist[v] + w
|
||||
heapq.heappush(pq, (dist[u], u))
|
||||
return dist
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
graph = {
|
||||
"Невский": [("Лиговский", 5), ("Гороховая", 3)],
|
||||
"Лиговский": [("Московский", 7)],
|
||||
"Гороховая": [("Московский", 4)],
|
||||
"Московский": [],
|
||||
}
|
||||
print(dijkstra(graph, "Невский"))
|
||||
Reference in New Issue
Block a user