# Python program to find Shortest Path using Dial's Algorithm
import sys
from collections import defaultdict
def shortestPath(n, src, edges):
adj = [[] for _ in range(n)]
maxWeight = 0
# Build adjacency list and find maximum weight
for e in edges:
adj[e[0]].append([e[1], e[2]])
adj[e[1]].append([e[0], e[2]])
maxWeight = max(maxWeight, e[2])
# Initialize distance array
dist = [sys.maxsize] * n
dist[src] = 0
# Create buckets for distances
maxDist = (n - 1) * maxWeight
buckets = defaultdict(set)
# Add source to bucket 0
buckets[0].add(src)
# Process buckets in order
for d in range(maxDist + 1):
# Process all nodes in current bucket
while d in buckets and buckets[d]:
u = buckets[d].pop()
# Skip if we already found a better path
if d > dist[u]:
continue
# Process all adjacent nodes
for edge in adj[u]:
v, weight = edge[0], edge[1]
newDist = dist[u] + weight
# If shorter path found
if newDist < dist[v]:
# Remove from old bucket if it was there
if dist[v] != sys.maxsize:
buckets[dist[v]].discard(v)
# Update distance and add to new bucket
dist[v] = newDist
buckets[newDist].add(v)
return dist
if __name__ == "__main__":
n = 9
src = 0
edges = [
[0, 1, 4],
[0, 7, 8],
[1, 2, 8],
[1, 7, 11],
[2, 3, 7],
[2, 8, 2],
[3, 4, 9],
[3, 5, 14],
[4, 5, 10],
[5, 6, 2],
[6, 7, 1],
[6, 8, 6],
[7, 8, 7]
]
res = shortestPath(n, src, edges)
for val in res:
print(val, end=" ")
print()