Shortest path in Undirected Graph with unit weights

Posted by N.K. Chauhan on Mar 31, 2024

Given an adjacency list of an undirected graph with "v" vertices (0 to v-1) and a source node "source".

The task is to find the shortest path possible from the source node to every other node in the graph.

It is given that the distance between any two adjacent nodes in the graph is 1.


Solutions

Method 1: Using BFS

As the distance between any two adjacent nodes in the graph is 1, we can calculate any node's distance by adding 1 to the distance of its previous node.

We will use a distance[] array initialised to INT_MAX. It will be used to keep track of each node's distance from the source node.

Start traversing the graph in a BFS manner and if any node's current distance is less than the distance already mentioned in the distance[] array, update it.

Complexity

The time complexity of this solution is O(v+e) and space complexity is O(v).

Related


Graph representation in Java (Matrix and List)

Depth-First Traversal (DFS) for a graph

Bellman-Ford Algorithm - Shortest Distance with Negative Edge

Dijkstra's Single Source Shortest Path Algorithm

Detect cycle in an undirected graph

Topological Sorting (Using BFS or DFS)

Check whether a given graph is Bipartite or not

Breadth First Search or BFS for a Graph

Minimum Spanning Tree (Prim's and Kruskal's algorithm)

Detect Cycle in a Directed Graph (Using BFS or DFS)