Shortest path in Undirected Graph with unit weights

Posted by 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


Depth-First Traversal (DFS) for a graph

Graph representation in Java (Matrix and List)

Check whether a given graph is Bipartite or not

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

Dijkstra's Single Source Shortest Path Algorithm

Topological Sorting (Using BFS or DFS)

Detect cycle in an undirected graph

Breadth First Search or BFS for a Graph

Bellman-Ford Algorithm - Shortest Distance with Negative Edge

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