The bug I almost shipped: I marked v as visited right at the start of BFS, which completely blocks it from ever being rediscovered.
Remove node v from the graph, then run BFS from each outgoing neighbor of v to find the shortest path back to v. The shortest cycle through v is 1 + the minimum of these distances. If no path exists, return -1.
Pro tip: Clarify whether the graph is unweighted (BFS) or weighted (Dijkstra), and mention that the cycle must be simple (no repeated nodes) to avoid trivial cycles. Also, consider edge cases like self-loops or multiple edges.
Confirm if the graph is directed, unweighted or weighted, and whether cycles are simple. Ask about constraints on graph size and edge weights.
Temporarily remove node v from the graph to prevent trivial cycles. Initialize a variable to track the minimum cycle length.
For each neighbor u of v, run BFS (or Dijkstra if weighted) from u to find the shortest path back to v without passing through v again.
For each path found, the cycle length is 1 (edge v->u) plus the path length from u to v. Keep the minimum over all neighbors.
If no cycle is found, return -1; otherwise, return the minimum cycle length.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.