Testing whether a graph is acyclic
by Robert M. Keller
Get an idea of an informal algorithm for testing graphs.
Show how to use our information structure list representations and functions to determine whether a graph is acyclic.
If a graph is acyclic, then it must have at least one node with no targets (called a leaf).
If we keep peeling off leaf nodes, one of two things will happen:
We will eventually peel off all nodes: The graph is acyclic.
We will get to a point where there is no leaf, yet the graph is not empty: The graph is cyclic.
1. If the graph has no nodes, stop. The graph is acyclic.
2. If the graph has no leaf, stop. The graph is cyclic.
3. Choose a leaf of the graph. Remove this leaf and all arcs going into the leaf to get a new graph.
4. Go to 1.
Each time we go from 4 to 1, we do so with a graph which has one fewer node.
Thus, in a number of steps at most equal to the number of nodes in the original graph, the algorithm must terminate.
(Pair) => first(Pair) == Node
no((Pair) => first(Pair) == Node, Graph);
no_leaf(Graph) = find_leaf(Graph) == [ ];
remove_duplicates(leaves(Graph));
1. If the Graph has no nodes, stop. The original graph is acyclic.
2. If the graph has no leaf, stop. The graph is cyclic.
3. Choose a leaf of Graph. Remove this leaf and all arcs going into the leaf to get a new graph.
4. Go to 1.
drop((Pair) => second(Pair) == Leaf, Graph);
(Pair) => second(Pair) == Leaf
remove_leaf(first(find_leaf(Graph)), Graph);
P ? T : F
acyclic(Graph) =
Graph == [ ] ? 1 // empty graph is acyclic
: no_leaf(Graph) ? 0 // graph with no leaf is cyclic
: acyclic(remove_leaf(Graph)); // try reduced graph
rex acyclic.rex