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 theshortest 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.

Input: n =7, edges =[[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]Output: 3Explanation: The cycle with the smallest length is:0->1->2->0

Input: n =4, edges =[[0,1],[0,2]]Output: -1Explanation: There are no cycles inthis graph.
To find the shortest cycle in an undirected graph, we can use BFS from every node. If we revisit a node (other than the parent) during BFS, we’ve found a cycle. The shortest such cycle across all BFS runs is the answer.
Track the distance from the start node and the parent for each node.
If you reach a neighbor that is not the parent and already visited, a cycle is found. The cycle length is the sum of distances to the two nodes plus one.
classSolution {
funfindShortestCycle(n: Int, edges: Array<IntArray>): Int {
val g = List(n) { mutableListOf<Int>() }
for (e in edges) {
g[e[0]].add(e[1])
g[e[1]].add(e[0])
}
var ans = Int.MAX_VALUE
for (i in0 until n) {
val dist = IntArray(n) { -1 }
val par = IntArray(n) { -1 }
val q = ArrayDeque<Int>()
dist[i] = 0 q.add(i)
while (q.isNotEmpty()) {
val u = q.removeFirst()
for (v in g[u]) {
if (dist[v] == -1) {
dist[v] = dist[u] + 1 par[v] = u
q.add(v)
} elseif (par[u] != v) {
ans = minOf(ans, dist[u] + dist[v] + 1)
}
}
}
}
returnif (ans ==Int.MAX_VALUE) -1else ans
}
}
classSolution:
deffindShortestCycle(self, n: int, edges: list[list[int]]) -> int:
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
ans = float('inf')
for i in range(n):
dist = [-1] * n
par = [-1] * n
q = [i]
dist[i] =0for u in q:
for v in g[u]:
if dist[v] ==-1:
dist[v] = dist[u] +1 par[v] = u
q.append(v)
elif par[u] != v:
ans = min(ans, dist[u] + dist[v] +1)
return-1if ans == float('inf') else ans