#C11501. Shortest Path Between Two Nodes
Shortest Path Between Two Nodes
Shortest Path Between Two Nodes
You are given an undirected graph with N nodes and M edges. Your task is to determine whether there exists a path between two given nodes, A and B. If such a path exists, compute the length of the shortest path between these nodes.
The graph is unweighted and may consist of disconnected components. The solution should use a breadth-first search (BFS) algorithm. Recall that BFS explores nodes level by level, and the shortest path length from the starting node A to any other reachable node is the number of edges in the path.
Note: When \( A = B \), the shortest path length is \(0\).
inputFormat
The input is read from stdin and has the following format:
N M u1 v1 u2 v2 ... uM vM A B
Here, the first line contains two integers: N (the number of nodes) and M (the number of edges). The next M lines each contain two integers representing an edge between nodes u and v. The last line contains two integers, A and B, denoting the start and destination nodes, respectively.
outputFormat
The output should be written to stdout. It consists of a single integer: the length of the shortest path from node A to node B. If no such path exists, output -1
.
6 7
1 2
2 3
3 4
4 5
5 6
1 6
2 5
1 4
3