How to Find the Shortest Path in an Unweighted Graph (BFS)
A step-by-step guide on how to use Breadth First Search to find the shortest path between two nodes in an unweighted graph.
Understand Why BFS Works Here
In an unweighted graph, every edge costs exactly one step. BFS explores the graph level by level, meaning it visits all nodes one step away first, then two steps away, and so on. The first time it reaches the destination, it has taken the shortest possible route.
Initialize the Required Structures
Create a Queue and add the starting node to it. Create a Visited Set and mark the starting node as visited immediately. Create a Distance Map and set the distance of the starting node to zero.
Begin the BFS Loop
Start a loop that continues as long as the queue is not empty. In each iteration, dequeue the node at the front of the queue and work with it.
Check if You Reached the Destination
After dequeuing a node, check if it is your destination. If it is, look up its value in the Distance Map and return it. That value is your shortest path length.
Explore All Neighbors
If the current node is not the destination, retrieve all its neighboring nodes from the adjacency list or matrix. For each neighbor, check if it has already been visited.
Process Unvisited Neighbors
If a neighbor has not been visited, mark it as visited immediately. Set its distance to the current node's distance plus one. Add it to the back of the queue so it gets explored in a future iteration.
Handle the No Path Case
If the loop finishes and the queue becomes empty without ever finding the destination, no path exists between the two nodes. Return negative one or infinity to indicate this.
Ready to master this completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

