There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1. The edges in the graph are represented by a given 2D integer array edges, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
Return the length of the shortest cycle in the graph. If no cycle exists, return -1.
A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.
Example 1:
Input: n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]
Output: 3
Explanation: The cycle with the smallest length is : 0 -> 1 -> 2 -> 0
Example 2:
Input: n = 4, edges = [[0,1],[0,2]]
Output: -1
Explanation: There are no cycles in this graph.
Constraints:
2 <= n <= 1000
1 <= edges.length <= 1000
edges[i].length == 2
0 <= ui, vi < n
ui != vi
There are no repeated edges.
Solutions
Solution 1: Enumerate edges + BFS
Thinking
The shortest cycle can be found by deleting each edge and computing the shortest path between its ends. \(n,m \le 1000\) makes \(O(m(n+m))\) BFS affordable.
Any cycle uses some edge \((u,v)\); after deleting it, \(\mathrm{dist}(u,v)+1\) is the shortest cycle through that edge. We take the minimum over all edges, or report no cycle if none reconnects.
We first construct the adjacency list \(g\) of the graph according to the array \(edges\), where \(g[u]\) represents all the adjacent vertices of vertex \(u\).
Then we enumerate the two-directional edge \((u, v)\), if the path from vertex \(u\) to vertex \(v\) still exists after deleting this edge, then the length of the shortest cycle containing this edge is \(dist[v] + 1\), where \(dist[v]\) represents the shortest path length from vertex \(u\) to vertex \(v\). We take the minimum of all these cycles.
The time complexity is \(O(m^2)\) and the space complexity is \(O(m + n)\), where \(m\) and \(n\) are the length of the array \(edges\) and the number of vertices.
Solution 1 runs BFS once per edge. Starting BFS from every vertex is enough: the first already-visited neighbor that is not the parent closes a cycle of length \(\mathrm{dist}(u)+\mathrm{dist}(v)+1\).
When the graph is denser this does fewer searches, \(O(n(n+m))\), and avoids deleting edges.
Similar to Solution 1, we first construct the adjacency list \(g\) of the graph according to the array \(edges\), where \(g[u]\) represents all the adjacent vertices of vertex \(u\).
Then we enumerate the vertex \(u\), if there are two paths from vertex \(u\) to vertex \(v\), then we currently find a cycle, the length is the sum of the length of the two paths. We take the minimum of all these cycles.
The time complexity is \(O(m \times n)\) and the space complexity is \(O(m + n)\), where \(m\) and \(n\) are the length of the array \(edges\) and the number of vertices.