Shortest Path using BFS

 

Osaka Castle Walls, Japan

This is a continuation of my earlier post on Breadth First Search, and highlights some key elements for determining the shortest path in an unweighted graph


Tracking edges

By applying BFS, we can traverse the graph and track the edges for all unvisited nodes. Optionally, we can also track the distance of the current node from the start node. This can be calculated by adding 1 to the value of the previous node in the edge.

Data Structure

A map, dictionary or an array is a data structure best suited to keep track of the edges and the counts, as it would allow easy lookup of the previous node and count.


Solving the problem

With the data in our hash table it now becomes possible to work backwards from the end node towards the start node to arrive at our solution

References

https://www.youtube.com/watch?v=5mG-qBRhvKQ

https://www.youtube.com/watch?v=oDqjPvD54Ss