Distance to a Cycle in Undirected Graph - Problem
You are given a positive integer n representing the number of nodes in a connected undirected graph containing exactly one cycle. The nodes are numbered from 0 to n - 1 (inclusive).
You are also given a 2D integer array edges, where edges[i] = [node1i, node2i] denotes that there is a bidirectional edge connecting node1i and node2i in the graph.
The distance between two nodes a and b is defined to be the minimum number of edges that are needed to go from a to b.
Return an integer array answer of size n, where answer[i] is the minimum distance between the ith node and any node in the cycle.
Input & Output
Example 1 — Basic Cycle with Branches
$
Input:
n = 7, edges = [[1,2],[2,4],[4,3],[3,1],[0,1],[5,4],[6,5]]
›
Output:
[1,0,0,0,0,1,2]
💡 Note:
The cycle is nodes 1→2→4→3→1. Node 0 is distance 1 from cycle node 1. Node 5 is distance 1 from cycle node 4. Node 6 is distance 2 from cycle (via node 5 to node 4).
Example 2 — Simple Triangle
$
Input:
n = 3, edges = [[0,1],[1,2],[2,0]]
›
Output:
[0,0,0]
💡 Note:
All nodes 0, 1, 2 form the cycle, so distance to cycle is 0 for all nodes.
Example 3 — Cycle with Long Chain
$
Input:
n = 6, edges = [[0,1],[1,2],[2,0],[3,1],[4,3],[5,4]]
›
Output:
[0,0,0,1,2,3]
💡 Note:
Cycle is 0→1→2→0. Node 3 connects to cycle node 1 (distance 1). Node 4 connects via node 3 (distance 2). Node 5 connects via nodes 4→3→1 (distance 3).
Constraints
- 3 ≤ n ≤ 105
- n - 1 ≤ edges.length ≤ 105
- edges[i].length == 2
- 0 ≤ node1i, node2i ≤ n - 1
- node1i != node2i
- The graph is connected.
- The graph has exactly one simple cycle.
Visualization
Tap to expand
Understanding the Visualization
1
Input Graph
Connected graph with exactly one cycle and some nodes branching off
2
Find Cycle
Use DFS to identify all nodes that are part of the cycle
3
Calculate Distances
Multi-source BFS from cycle nodes to find minimum distances
Key Takeaway
🎯 Key Insight: Find the cycle first using DFS, then run multi-source BFS from all cycle nodes to efficiently compute minimum distances in one pass
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code