The edge that closes the cycle
Warm-up · Trace the algorithm · about 4 min
DFS starts at node 0 and tries edges in the order they are listed: 0→1, 0→2, 1→3, 2→3, 3→4, 4→2. Click the edge DFS flags first as closing a cycle.
Example 1
Input:
{"edges":[[0,1],[0,2],[1,3],[2,3],[3,4],[4,2]],"source":0}
Output:
["2-3"]
Only an edge into a gray node closes a cycle.
Constraints
- Edges are tried in the order they are listed.
Learn the idea first: Cycle detection in undirected and directed graphs, a visual lesson.
More Cycle detection in undirected and directed graphs problems
- Detect a cycle Standard
- Course schedule Standard
- Spot the bug: every edge is a cycle Standard
- Find the cycle itself Challenge