Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

import sys

# Function to find the shortest path between a given source vertex and all other
vertices
# in the given graph using Dijkstra's algorithm
def dijkstra(graph, src):

# Initialize distances of all vertices as infinite and distance to source as 0


distances = [float("inf") for _ in range(len(graph))]
distances[src] = 0

# Create a set to store the vertices that have been visited


visited = set()

# Iterate until all vertices have been visited


while len(visited) != len(graph):

# Find the vertex with the smallest distance


min_distance = float("inf")
min_vertex = -1
for i in range(len(graph)):
if i not in visited and distances[i] < min_distance:
min_distance = distances[i]
min_vertex = i

# Mark the vertex as visited


visited.add(min_vertex)

# Update the distances of the neighboring vertices


for neighbor, weight in graph[min_vertex]:
if neighbor not in visited:
distances[neighbor] = min(distances[neighbor],
distances[min_vertex] + weight)

# Return the distances


return distances

# Example usage

# Create a graph as an adjacency list


graph = [[(1, 3), (2, 1)], # vertex 0
[(3, 1)], # vertex 1
[(1, 1), (3, 3)], # vertex 2
[]] # vertex 3

# Find the shortest path

You might also like