Given a graph with V vertices and E edges and two vertices u, v present in the graph. Find the minimum number of edges in the path between these two vertices. If the path doesn't exist, return -1.
[Naive Approach] Using DFS - O(N!) time and O(V) space
The idea is to perform a DFS traversal starting from vertex u. From each vertex, we recursively explore all possible paths to reach the destination vertex v, keeping track of the number of edges traversed. Whenever we reaches to v, we update the minimum count among all discovered paths. If no path is found after exploring all possibilities, we return -1.
Output
2
[Expected Approach] Using BFS - O(V+E) time and O(V) space
The idea is to perform a BFS starting from the source vertex while tracking the level (or distance) of each vertex. The first time the destination vertex is reached, the current level represents the minimum number of edges between the two nodes.
This works because BFS explores the graph level by level β it visits all nodes at distance 1 before distance 2, and so on. Hence, when we first encounter the destination, itβs guaranteed to be through the shortest possible path.