Unit 03
Unit 03
No :
SHORTEST PATH OF A GRAPH
Date :
AIM:
To implement the python programming for finding the shortest path of a graph.
Given a weighted graph and a source vertex in the graph, find the shortest paths from the
source to all the other vertices in the given graph.
Note: The given graph does not contain any negative edge.
PSEUDOCODE:
Initialize: Set the source node's distance to 0, and all others to infinity. Use a priority queue.
Update: For each node, update its neighbors' distances if a shorter path is found.
Repeat: Extract the node with the smallest distance from the queue and repeat until all nodes
are processed.
Running Time: O(n2)
Memory Complexity: O (n2)
SOURCE CODE:
for _ in range(num_nodes):
min_distance = float('inf')
current_node = -1
for node in range(num_nodes):
if not visited[node] and distances[node] < min_distance:
min_distance = distances[node]
current_node = node
visited[current_node] = True
18 717823I260
for neighbor in range(num_nodes):
if graph[current_node][neighbor] != 0 and not visited[neighbor]:
new_distance = distances[current_node] + graph[current_node][neighbor]
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
return distances
def get_graph_input():
num_vertices = int(input("Enter the number of vertices: "))
graph = []
print("Enter the adjacency matrix row by row (space-separated values):")
for i in range(num_vertices):
row = list(map(int, input(f"Row {i + 1}: ").strip().split()))
graph.append(row)
start_vertex = int(input("Enter the starting vertex (0 to {}): ".format(num_vertices - 1)))
return graph, start_vertex
graph, start_vertex = get_graph_input()
distances = dijkstra(graph, start_vertex)
print("Shortest distances from node {}: {}".format(start_vertex, distances))
OUTPUT:
RESULT:
Thus the python program for finding the shortest path of a graph was executed successfully and the
output is verified.
19 717823I260