29 lines
888 B
Python
29 lines
888 B
Python
def shortest_path(number_of_nodes, connections):
|
|
graph = [[] for i in range(number_of_nodes)]
|
|
|
|
for a, b, distance in connections:
|
|
graph[a].append((b, distance))
|
|
graph[b].append((a, distance))
|
|
|
|
distances = [float('inf')] * number_of_nodes
|
|
paths = [None] * number_of_nodes
|
|
visited = [False] * number_of_nodes
|
|
|
|
distances[0] = 0
|
|
paths[0] = [0]
|
|
for i in range(number_of_nodes):
|
|
current = -1
|
|
|
|
for j in range(number_of_nodes):
|
|
if not visited[j]:
|
|
if current == -1 or distances[j] < distances[current]:
|
|
current = j
|
|
|
|
if current == -1 or distances[current] == float('inf'):
|
|
break
|
|
|
|
visited[current] = True
|
|
|
|
for neighbor, weight in graph[current]:
|
|
new_distance = distances[current] + weight
|
|
new_path = paths[current] + [neighbor] |