Computing the Minimum Number of Flight Segments

If we want to compute the minimum number of flight segments between a starting city and target city, we can construct an undirected graph.  In the graph the nodes represent cities and the edges represent the flight segments.  We can count the number of segments to determine the shortest distance.

The following can be applied to any situation in finding the shortest path.  It is an implementation of the breadth first search algorithm.

See code below.

Problem: Given an undirected graph with n vertices and m edges and two vertices u and v, compute the length of a shortest path between u and v (that is, the minimum number of edges in a path from u to v).

Input Format: An undirected graph with n vertices and m edges. The next line contains two vertices u and v of the graph.

Constraints: 2 ≤ n ≤ 10^5 , 0 ≤ m ≤ 10^5 , u 6 = v, 1 ≤ u, v ≤ n.

Result: Integer value of the minimum number of edges in a path from u to v, or −1 if there is no path.