Given an unweighted, undirected graph with n nodes (labeled 0 to n-1) and a list of edges, find the length of the shortest path between a given source node and a destination node. If no path exists, return -1.
Output: 4
Explanation: Shortest path is 0 → 1 → 3 → 4 → 5, which has length 4.
Output: -1
Explanation: Node 3 is disconnected; no path exists from 0 to 3.
BFS is the natural choice for finding the shortest path in an unweighted graph because it explores nodes level by level, guaranteeing that the first time we reach the destination it is via the shortest route.
- Build an adjacency list from the edge list.
- Start BFS from the source node, maintaining a visited set to avoid revisiting nodes.
- Track the current distance (level). For each neighbor not yet visited, enqueue it.
- Return the distance when the destination is dequeued. If the queue empties without finding the destination, return -1.
Complexity Analysis:
Time complexity: O(V + E) where V is the number of vertices and E is the number of edges.
Space complexity: O(V + E) for the adjacency list, visited array, and BFS queue.