AlgoFrames

Find the cycle itself

Challenge · Write code · about 20 min

Given a directed graph, return the nodes of one cycle in order: [c0, c1, …, ck] where every edge c0 → c1, …, ck → c0 exists and no node repeats. A self-loop is the cycle [v]. Return [] when the graph has no cycle. Any correct cycle is accepted.

Example 1

Input:

[{"n":5,"edges":[[0,1],[1,2],[2,3],[3,1],[3,4]],"directed":true}]

Output:

[1,2,3]

[2, 3, 1] and [3, 1, 2] are also accepted.

Example 2

Input:

[{"n":3,"edges":[[0,1],[1,2],[0,2]],"directed":true}]

Output:

[]

No path comes back to where it started.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ edges ≤ 200
  • No edge appears twice.

Learn the idea first: Cycle detection in undirected and directed graphs, a visual lesson.

More Cycle detection in undirected and directed graphs problems