AlgoFrames

Detect a cycle

Standard · Write code · about 12 min

Return true when the graph contains a cycle, and false otherwise. graph.directed says whether edges are one-way. In a directed graph a cycle follows edge directions. In an undirected graph a cycle needs at least three different edges or a self-loop.

Example 1

Input:

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

Output:

true

1 → 2 → 3 → 1 is a cycle.

Example 2

Input:

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

Output:

false

Two paths meet at 3, but no path returns to its start.

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