Graph Girth
Problem Link
Tags: BFSTime Complexity: O(N²)
In this problem, an undirected unweighted graph is given, and we are asked to find the length of the shortest cycle, if any.
Since the graph edges are unweighted, BFS can be used to find the shortest path from the starting node to all other nodes. But, we do not know which nodes are part of the cycle, so where do we start the BFS?
Since N ≤ 2500, we can run BFS from every node and keep track of the shortest cycle length. For each BFS-run, we keep track of the number of edges traversed (aka distance) to reach the current node from the starting node. If we visit a node that has already been visited, then it means the shortest cycle that includes the starting node has been found. Let's call this node y and call the node which visited node y for a second time, x. To find the length of this cycle, simply add the distance travelled by the x, to the distance travelled by node y and one to include the edge between x and y.
The answer is the minimum of all the cycle lengths.
Comments