Skip to content

2.1 Find out whether a graph has a cycle, and show one

You find out whether a graph is a DAG (directed acyclic graph), and get one of its cycles as a list of nodes.

You want to be sure that following the edges of a graph never leads back to the same node. A path that does is called a cycle. If the graph has a cycle, you want to show it, so that someone can find and fix it. You need this wherever edges stand for an order that must exist:

  • dependencies between modules that must be built one after the other;
  • steps of a process that must run in order;
  • a hierarchy of categories, in which no category may contain itself.

The example graph dependencies models the dependencies between the packages of a small program. It has an edge from each package to each package it uses. Is the graph free of cycles, and if not, where is a cycle? The picture after shows the cycle found: model and storage use each other.

The packages and their dependencies
The cycle of model and storage
0: app1: cli2: ui3: service4: model5: storage6: json7: util
0: app1: cli2: ui3: service4: model5: storage6: json7: util
Context
  • Edge of the cycle
Output
  • Node of the cycle
boolean dependenciesAcyclic = Graphs.isDag(dependencies); // false
// [4, 5] - model, storage
IntList cycle = Graphs.findCycle(dependencies);
Full example
let dependencies_acyclic = graphs::is_dag(&dependencies); // false
let cycle = graphs::find_cycle(&dependencies); // [4, 5] - model, storage
Full example
const dependenciesAcyclic = Graphs.isDag(dependencies); // false
const cycle = Graphs.findCycle(dependencies); // [4, 5] - model, storage
Full example
bool dependenciesAcyclic = Graphs.IsDag(dependencies); // false
// [4, 5] - model, storage
ImmutableArray<int> cycle = Graphs.FindCycle(dependencies);
Full example

The packages are not a DAG (directed acyclic graph). Graphs.findCyclegraphs::find_cycleGraphs.findCycleGraphs.FindCycle returns the nodes of a cycle in the order of its edges. An edge leads from each node to the next, and from the last node back to the first. Here the cycle is model -> storage -> model, with the green nodes and the orange edges of the picture after.