Skip to contentKEEP THE CRAFTTHE SANCTUARY

Detect a Directed Cycle

Find a cycle in a directed graph with DFS and three node states: unvisited, on the current path, and finished.

The problem

Implement has_directed_cycle(node_count, edges). The nodes are labeled 0 to node_count - 1, and each edge [a, b] goes one way, from a to b. Return True if you can start at some node, follow edges and come back to it (a self-loop [a, a] counts), and False otherwise. The graph may be empty or split into several disconnected parts. 0 <= node_count <= 500. For example, edges [[0, 1], [1, 2], [2, 0]] form a cycle, but [[0, 1], [0, 2], [1, 3], [2, 3]] do not, even though node 3 can be reached twice.

Starter code

def has_directed_cycle(node_count, edges):
    pass

Public examples

  1. node_count = 3, edges = [[0, 1], [1, 2], [2, 0]]givesTrue
  2. node_count = 4, edges = [[0, 1], [0, 2], [1, 3], [2, 3]]givesFalse

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.