-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
39 lines (31 loc) · 847 Bytes
/
main.py
File metadata and controls
39 lines (31 loc) · 847 Bytes
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
29
30
31
32
33
34
35
36
37
38
39
def dijkstra(Grafo, salida):
dist, prev = {}, {}
result = []
for vertice in Grafo:
dist[vertice] = float("inf")
prev[vertice] = None
dist[salida] = 0
Q = [vertice for vertice in Grafo]
while Q:
u = min(Q, key=dist.get)
Q.remove(u)
result.append(u)
for vecino in Grafo[u]:
if vecino in Q and dist[vecino] > dist[u] + Grafo[u][vecino]:
dist[vecino] = dist[u] + Grafo[u][vecino]
prev[vecino] = u
return result, dist, prev
grafo = {
'a': {'b': 4, 'c': 3},
'b': {'d': 5},
'c': {'b': 2, 'd': 3, 'e': 6},
'd': {'f': 5, 'e': 1},
'e': {'g': 5},
'g': {'z': 4},
'f': {'g': 2, 'z': 7},
'z': {}
}
s, distancia, previos = dijkstra(grafo, 'a')
print(f"{s=}")
print(f"{distancia=}")
print(f"{previos=}")