Lesson 2 · Unit 03
Finding cycles
Three states for directed graphs, a parent check for undirected
What you practise
- Kahn's leftovers
- Three-state DFS
- The parent check in undirected graphs
Try a question from this lesson
Pick one
Task A waits for B, B waits for C, and C waits for A. Which task can start first?
Correct answer
None: each one waits on another forever
Why
The three arrows form a cycle, so every task has an unmet prerequisite. Build tools and spreadsheets look for exactly this and report a "circular dependency" before doing any work.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Three states
A depth-first search can find a cycle by giving each node a state: 0 is not visited, 1 is on the path being explored right now, 2 is finished.
An edge into a node in state 1 leads back onto your own path: a cycle. An edge into state 2 is harmless.
def has_cycle(adj):
n = len(adj)
state = [0] * n
def visit(node):
if state[node] != 0:
return state[node] == 1
state[node] = 1
for nxt in adj[node]:
if visit(nxt):
return True
state[node] = 2
return False
return any(visit(v) for v in range(n))function hasCycle(adj) {
const state = adj.map(() => 0);
function visit(node) {
if (state[node] === 1) return true;
if (state[node] === 2) return false;
state[node] = 1;
for (const nxt of adj[node]) {
if (visit(nxt)) return true;
}
state[node] = 2;
return false;
}
return adj.some((_, v) => visit(v));
}function hasCycle(adj: number[][]) {
const state = adj.map(() => 0);
function visit(node: number): boolean {
if (state[node] === 1) return true;
if (state[node] === 2) return false;
state[node] = 1;
for (const nxt of adj[node]) {
if (visit(nxt)) return true;
}
state[node] = 2;
return false;
}
return adj.some((_, v) => visit(v));
}Python noteany(...) tries a search from every node and stops at the first one that reports a cycle, so no part of the graph is missed.
JavaScript noteadj.some((_, v) => visit(v)) tries a search from every index and stops at the first one that returns true.
TypeScript notevisit calls itself, so TypeScript cannot infer what it returns: the : boolean must be written out.
Concept
Undirected: skip the parent
In an undirected graph, each node sees the node it was reached from among its neighbours. Pass that parent along and ignore it.
Any other neighbour that is already seen closes a loop. The start has no parent, so pass -1.
def loops(adj, node, parent, seen):
seen.add(node)
for nxt in adj[node]:
if nxt == parent:
continue
if nxt in seen:
return True
if loops(adj, nxt, node, seen):
return True
return Falsefunction loops(adj, node, parent, seen) {
seen.add(node);
for (const nxt of adj[node]) {
if (nxt === parent) continue;
if (seen.has(nxt)) return true;
if (loops(adj, nxt, node, seen)) {
return true;
}
}
return false;
}function loops(
adj: number[][],
node: number,
parent: number,
seen: Set<number>,
): boolean {
seen.add(node);
for (const nxt of adj[node]) {
if (nxt === parent) continue;
if (seen.has(nxt)) return true;
if (loops(adj, nxt, node, seen)) {
return true;
}
}
return false;
}TypeScript noteseen: Set<number> is a set of node numbers. The one set is passed down through every call, so all of them share it.
8 more exercises in the app
- 4× multiple choice
- 1× type the answer
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.