Distance to a Cycle in Undirected Graph - Problem
Finding Distances to the Cycle in a Connected Graph
You're given a special type of connected undirected graph with exactly one cycle. Think of it like a tree with one extra edge that creates a single loop. Your task is to find how far each node is from this cycle.
Given:
•
• A 2D array
• The graph is connected and contains exactly one cycle
Goal: Return an array where
Distance is defined as the minimum number of edges needed to travel between two nodes.
You're given a special type of connected undirected graph with exactly one cycle. Think of it like a tree with one extra edge that creates a single loop. Your task is to find how far each node is from this cycle.
Given:
•
n nodes numbered from 0 to n-1• A 2D array
edges where edges[i] = [node1, node2] represents bidirectional connections• The graph is connected and contains exactly one cycle
Goal: Return an array where
answer[i] is the minimum distance from node i to any node in the cycle.Distance is defined as the minimum number of edges needed to travel between two nodes.
Input & Output
example_1.py — Basic Cycle
$
Input:
n = 7, edges = [[1,2],[2,4],[4,3],[3,1],[0,1],[5,2],[6,5]]
›
Output:
[1,0,0,0,0,1,2]
💡 Note:
Nodes 1,2,3,4 form a cycle. Node 0 is 1 edge from node 1 (cycle). Node 5 is 1 edge from node 2 (cycle). Node 6 is 2 edges from the cycle (6→5→2).
example_2.py — Triangle Cycle
$
Input:
n = 4, edges = [[0,1],[1,2],[2,0],[3,0]]
›
Output:
[0,0,0,1]
💡 Note:
Nodes 0,1,2 form a triangle cycle. Node 3 is connected to node 0 (cycle node) so its distance is 1.
example_3.py — Single Self-Loop
$
Input:
n = 3, edges = [[0,1],[1,2],[2,1]]
›
Output:
[2,0,0]
💡 Note:
Nodes 1,2 form a cycle with 2 nodes. Node 0 is 2 edges away from the cycle (0→1→2 or 0→1, and 1 is in cycle so distance is 1, but 0→1 where 1 is in cycle gives distance 1).
Constraints
- 3 ≤ n ≤ 105
- n ≤ edges.length ≤ 105
- edges[i].length == 2
- 0 ≤ node1i, node2i ≤ n - 1
- node1i ≠ node2i
- The graph is connected
- The graph has exactly one cycle
- No multiple edges between same pair of nodes
Visualization
Tap to expand
Understanding the Visualization
1
Map the Neighborhood
Build a graph representation of all the streets connecting houses
2
Find the Central Loop
Use DFS to identify which houses are on the circular road (the cycle)
3
Start from the Loop
Begin BFS simultaneously from all houses on the circular road
4
Expand Outward
BFS naturally finds shortest distances to all houses on dead-end streets
Key Takeaway
🎯 Key Insight: Instead of calculating distances from each house individually, we start from the central loop and expand outward. This finds all distances in just one sweep - much like how emergency services would plan response times from a central station!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code