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


Breadth First Search or BFS for a Graph

Check whether a given graph is Bipartite or not

Dijkstra's Single Source Shortest Path Algorithm

Depth-First Traversal (DFS) for a graph

Graph representation in Java (Matrix and List)

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

Topological Sorting (Using BFS or DFS)

Bellman-Ford Algorithm - Shortest Distance with Negative Edge

Detect cycle in an undirected graph

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