Find a cycle in an undirected or directed graph, test for a valid tree, split a graph into two colours, and know when topological sort (A3) or union-find (A4) is the better tool.
You work on a parcel-delivery app. Parcels move between hubs on conveyor belts, and you must answer questions about a belt map before a new layout goes live. Graphs (S6) gave you the map, and BFS and DFS on any graph gave you the walk. This lesson uses that walk to ask three new questions.
Here is a small map. Six hubs are numbered 0 to 5. Each line is a two-way belt, so a parcel can move either way.
0 1
1 2
2 3
3 4
4 1
0 5Question 1: is there a cycle? A cycle is a route that leaves a hub, uses no belt twice, and comes back to the hub it left. Here, 1 to 2 to 3 to 4 and back to 1 is a cycle of four belts. The layout tool rejects a map with a cycle when it needs exactly one route between any two hubs.
Question 2: can the hubs get two colours? Two hubs joined by a belt are never serviced in the same window. So give each hub window A or window B, with no belt joining two hubs of one window. A map that allows this is bipartite.
Question 3: is the map a tree? A tree is a map where every hub reaches every other hub by exactly one route. A map can fall into separate parts, and each part is a component. A tree is one component with no cycle.
One walk answers all three. After that, you do the same for one-way belts, where the rule for a cycle changes.
You walk through a town and put a chalk mark on every crossing you reach. You never turn back along the street you used last. If you reach a crossing that already has a mark, by a different street, you have walked in a loop.
The crossings are hubs, and the streets are belts. The chalk mark is the seen mark. The street you came by is the arrival belt. A marked hub reached by any other belt means a cycle.
A cycle is like walking through a town with chalk: reach a marked crossing by a different street, and you have walked in a loop.
Predict what happens
Q You walk the six-hub map from hub 0 and mark every hub you reach. At hub 3 you arrived from hub 4. Hub 3 also has a belt to hub 2, which is already marked. What does that tell you?
Answer: C
The belt from 3 to 2 is not the belt you arrived by, and hub 2 was marked earlier. Two routes to one hub make a cycle.
Every walk below keeps a seen mark on each hub and a list of hubs to visit, as in BFS and DFS on any graph. The first walk uses a stack, and the second a queue. A hub is marked when it joins the list, so it joins once.
Walk the six-hub map from hub 0 with a stack. Each entry holds a hub and the belt you arrived by. Take an entry, and look at every belt from that hub except the arrival belt. A belt to a seen hub means a cycle, and a belt to a new hub marks it and puts it on the stack.
| Step | Take | Arrived by | Stack after | Seen after |
|---|---|---|---|---|
| 1 | 0 | none | 1, 5 | 0, 1, 5 |
| 2 | 5 | belt 5 | 1 | 0, 1, 5 |
| 3 | 1 | belt 0 | 2, 4 | 0, 1, 2, 4, 5 |
| 4 | 4 | belt 4 | 2, 3 | 0, 1, 2, 3, 4, 5 |
| 5 | 3 | belt 3 | belt 2 leads to hub 2, already seen: a cycle |
The walk marks each hub as it is pushed and skips only the arrival belt; a belt to a hub already marked closes a cycle.
Now run the same walk on a map with no cycle: hubs 0 to 5 with belts 0-1, 0-2, 2-3, 2-4 and 4-5. The walk takes six entries, marks every hub, and the stack runs empty. No belt ever led to a seen hub, so there is no cycle.
A map can fall into several parts. A walk from hub 0 only reaches hub 0's part, so the code starts a new walk from every hub that is still unseen. A cycle in the second part would be missed otherwise.
Counting the parts gives a shortcut. A part with k hubs needs only k - 1 belts to reach every hub, so a map with c parts and no cycle has exactly n - c belts.
Take 8 hubs with belts 0-1, 1-2, 3-4 and 5-6. There are 4 parts: {0, 1, 2}, {3, 4}, {5, 6} and {7}. That is 8 - 4 = 4 belts, and the map has 4, so there is no cycle.
Add the belt 2-0, and 5 belts is more than 4, so a cycle exists.
Exercise · Find the bug: The tree that has a cycle. This check counts the parts of a two-way map, then compares the belts with n - parts. It reports a cycle on a plain chain of hubs. Which line is wrong?
def has_loop_by_count(n, edges):
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
seen = [False] * n
parts = 0
for start in range(n):
if seen[start]:
continue
parts += 1
seen[start] = True
stack = [start]
while stack:
hub = stack.pop()
for neighbour in adj[hub]:
if not seen[neighbour]:
seen[neighbour] = True
stack.append(neighbour)
return len(edges) >= n - partsColour with a queue. Give a start hub colour 0. Every neighbour gets the other colour and joins the queue. When a belt joins two hubs that already have the same colour, the colouring has failed.
On the map with belts 0-1, 1-2, 2-3, 3-0, 3-4 and 4-5, the walk goes like this. A dash means no colour yet.
| Step | Take | Queue after | Colours of hubs 0 to 5 |
|---|---|---|---|
| 1 | 0 | 1, 3 | 0, 1, -, 1, -, - |
| 2 | 1 | 3, 2 | 0, 1, 0, 1, -, - |
| 3 | 3 | 2, 4 | 0, 1, 0, 1, 0, - |
| 4 | 2 | 4 | 0, 1, 0, 1, 0, - |
| 5 | 4 | 5 | 0, 1, 0, 1, 0, 1 |
| 6 | 5 | 0, 1, 0, 1, 0, 1 |
The loop of four belts is fine. Now take belts 0-1, 1-2, 2-0 and 2-3: hub 0 gets colour 0, and hubs 1 and 2 both get colour 1. When the walk takes hub 1, its belt to hub 2 joins two hubs of colour 1, which is a clash. Two colours are not enough.
Colouring with a queue flips the colour at every belt; a belt between two hubs of one colour is a clash.
Predict what happens
Q A map has a loop of five belts and nothing else. Can its hubs be given two colours?
Answer: C
The colour flips at every belt. After an odd number of belts you are back at the start hub with the other colour, which is a clash. A loop of four or six belts works.
Exercise · Predict the output: Colours across separate parts. Six hubs, and the belts 0-1, 1-2 and 3-4. Hub 5 has no belt. The walk gives a hub colour 0 when it starts a new part, and the opposite colour to each hub it reaches. What does it print?
from collections import deque
n, edges = 6, [[0, 1], [1, 2], [3, 4]]
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
colour = [-1] * n
for start in range(n):
if colour[start] != -1:
continue
colour[start] = 0
queue = deque([start])
while queue:
hub = queue.popleft()
for nxt in adj[hub]:
if colour[nxt] == -1:
colour[nxt] = 1 - colour[hub]
queue.append(nxt)
print(*colour)A tree has no cycle and one part. It has exactly n - 1 belts: 5 hubs and belts 0-1, 0-2, 0-3 and 1-4 make a tree with 4 belts. Check the count first, because a map with another count is not a tree.
With exactly n - 1 belts, one walk from hub 0 decides everything. If it reaches every hub, the map is connected, and no belt is left for a cycle.
Exercise · Break it: Connected is not enough for a tree. This check says a map is a tree when one walk from hub 0 reaches every hub. Find a map where it answers yes and the map is not a tree.
def is_tree(n, edges):
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
seen = [False] * n
seen[0] = True
stack = [0]
while stack:
hub = stack.pop()
for neighbour in adj[hub]:
if not seen[neighbour]:
seen[neighbour] = True
stack.append(neighbour)
return all(seen)A one-way belt goes from one hub to another, so a cycle must follow the arrows. Two routes that meet at one hub are not a cycle, so a seen mark is not enough.
Give each hub one of three marks: new, on the path or finished. The path is the hubs between the start of the walk and where you are now. A hub is finished when all its belts are tried.
Walk the map with belts 0 to 1, 1 to 2, 2 to 3, 3 to 1, 3 to 4 and 0 to 5. From hub 0 the path grows to 0, 1, 2, 3. Then hub 3 has a belt back to hub 1, which is on the path. That closes the cycle 1, 2, 3.
In one-way belts, only a belt back to a hub on the current path closes a cycle; a finished hub does not.
Now take the diamond: belts 0 to 1, 0 to 2, 1 to 3 and 2 to 3. The walk goes to 0, 1, 3, and hub 3 finishes. Back at hub 0 it goes on to 2, and hub 2 has a belt to hub 3. Hub 3 is finished, not on the path, so it is a second route and not a cycle.
There is another test for one-way belts. Count the belts that point at each hub. A hub with count 0 waits for nothing, so settle it and remove its belts. Any hub that never reaches 0 waits for something in a loop.
This is Kahn's algorithm from Topological sort (A3), used here only as a loop test.
Step by step: Counting on belts with a loop. The animated player loads in your browser.
On the map above the queue runs dry after 2 of the 6 hubs. Hubs 1, 2, 3 and 4 never reach count 0, so the settled count is less than n, and there is a cycle. On the diamond all 4 hubs are settled, so there is none.
Predict what happens
Q One-way belts: 0 to 1, 0 to 2, 1 to 3 and 2 to 3. The walk reaches hub 3 a second time, from hub 2. Hub 3 is finished. Is that a cycle?
Answer: B
A cycle must come back to a hub still on the current path. A finished hub was left behind, so reaching it again only means two routes meet there.
Pick a map and run the count. Step forwards and back.
Try these four, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
When the walk marks a hub, it reaches it by exactly one belt. That belt is the hub's arrival belt. The hub you came from is always seen, so reaching it back along the same belt proves nothing.
Any other belt from a hub to a seen hub is a second way to reach that hub, and two ways to reach one hub close a cycle. If no such belt exists, every belt is an arrival belt, and the belts form a tree in each part.
Every seen hub was reached by one belt, its arrival belt. Any other belt to a seen hub gives it a second route and closes a cycle.
The belt number matters. Skip the arrival hub instead of the arrival belt, and two belts between the same hubs hide each other, so a cycle of two is missed.
Along any route, the colour flips at every belt. So a hub's colour is fixed by its number of belts from the start of its part. An even number gives colour 0, and an odd number gives colour 1.
A clash means two hubs joined by a belt have the same parity. The two routes from the start, plus that belt, make a cycle with an odd number of belts.
The colour of a hub is the parity of its route length from the start of its part. A clash exists exactly when the map has a cycle with an odd number of belts.
Every hub on the current path can reach the hub at the end of the path by following the path. So a belt from the end back to a hub on the path closes a loop. A finished hub is different: all its belts were tried and none led back to the path at that time. Reaching it again cannot close a cycle through the path.
Every hub on the current path can reach the hub at its end. So a belt back to a hub on the path closes a cycle, and a belt to a finished hub never does.
Predict what happens
Q In a walk over one-way belts, hub 5 is marked finished. Later another hub has a belt to hub 5. What should the walk do?
Answer: B
Hub 5 finished after all its belts were tried, and none led to a hub on the path. A belt to it only joins a second route.
The step markers [1] onwards match the steps above. The walk over two-way belts uses a stack and keeps each belt's number.
def has_loop(n, edges):
# [1] Build the neighbour lists. Each entry keeps its belt number, so two belts between the same hubs stay two belts.
adj = [[] for _ in range(n)]
for belt, (a, b) in enumerate(edges):
adj[a].append((b, belt))
adj[b].append((a, belt))
seen = [False] * n
# [2] Start a walk from every hub that no earlier walk reached.
for start in range(n):
if seen[start]:
continue
seen[start] = True
stack = [(start, -1)]
while stack:
# [3] Take a hub from the stack, with the belt that brought you to it.
hub, arrived = stack.pop()
# [4] Look at every belt from it except the belt you arrived by.
for neighbour, belt in adj[hub]:
if belt == arrived:
continue
# [5] A neighbour that is already seen is reached by a second belt: a loop.
if seen[neighbour]:
return True
# [6] A new neighbour is marked now and waits on the stack, so it is pushed once.
seen[neighbour] = True
stack.append((neighbour, belt))
# [7] No walk found a second belt to a seen hub: no loop.
return Falsepublic boolean hasLoop(int n, int[][] edges) {
// [1] Build the neighbour lists. Each entry keeps its belt number, so two belts between the same hubs stay two belts.
java.util.List<int[]>[] adj = new java.util.List[n];
for (int i = 0; i < n; i++) adj[i] = new java.util.ArrayList<>();
for (int belt = 0; belt < edges.length; belt++) {
adj[edges[belt][0]].add(new int[]{edges[belt][1], belt});
adj[edges[belt][1]].add(new int[]{edges[belt][0], belt});
}
boolean[] seen = new boolean[n];
// [2] Start a walk from every hub that no earlier walk reached.
for (int start = 0; start < n; start++) {
if (seen[start]) continue;
seen[start] = true;
java.util.ArrayDeque<int[]> stack = new java.util.ArrayDeque<>();
stack.push(new int[]{start, -1});
while (!stack.isEmpty()) {
// [3] Take a hub from the stack, with the belt that brought you to it.
int[] top = stack.pop();
int hub = top[0], arrived = top[1];
// [4] Look at every belt from it except the belt you arrived by.
for (int[] next : adj[hub]) {
int neighbour = next[0], belt = next[1];
if (belt == arrived) continue;
// [5] A neighbour that is already seen is reached by a second belt: a loop.
if (seen[neighbour]) return true;
// [6] A new neighbour is marked now and waits on the stack, so it is pushed once.
seen[neighbour] = true;
stack.push(new int[]{neighbour, belt});
}
}
}
// [7] No walk found a second belt to a seen hub: no loop.
return false;
}bool hasLoop(int n, vector<vector<int>> edges) {
// [1] Build the neighbour lists. Each entry keeps its belt number, so two belts between the same hubs stay two belts.
vector<vector<pair<int, int>>> adj(n);
for (int belt = 0; belt < (int)edges.size(); belt++) {
adj[edges[belt][0]].push_back({edges[belt][1], belt});
adj[edges[belt][1]].push_back({edges[belt][0], belt});
}
vector<bool> seen(n, false);
// [2] Start a walk from every hub that no earlier walk reached.
for (int start = 0; start < n; start++) {
if (seen[start]) continue;
seen[start] = true;
vector<pair<int, int>> stack;
stack.push_back({start, -1});
while (!stack.empty()) {
// [3] Take a hub from the stack, with the belt that brought you to it.
auto [hub, arrived] = stack.back();
stack.pop_back();
// [4] Look at every belt from it except the belt you arrived by.
for (auto [neighbour, belt] : adj[hub]) {
if (belt == arrived) continue;
// [5] A neighbour that is already seen is reached by a second belt: a loop.
if (seen[neighbour]) return true;
// [6] A new neighbour is marked now and waits on the stack, so it is pushed once.
seen[neighbour] = true;
stack.push_back({neighbour, belt});
}
}
}
// [7] No walk found a second belt to a seen hub: no loop.
return false;
}function hasLoop(n, edges) {
// [1] Build the neighbour lists. Each entry keeps its belt number, so two belts between the same hubs stay two belts.
const adj = Array.from({ length: n }, () => []);
edges.forEach(([a, b], belt) => {
adj[a].push([b, belt]);
adj[b].push([a, belt]);
});
const seen = new Array(n).fill(false);
// [2] Start a walk from every hub that no earlier walk reached.
for (let start = 0; start < n; start++) {
if (seen[start]) continue;
seen[start] = true;
const stack = [[start, -1]];
while (stack.length > 0) {
// [3] Take a hub from the stack, with the belt that brought you to it.
const [hub, arrived] = stack.pop();
// [4] Look at every belt from it except the belt you arrived by.
for (const [neighbour, belt] of adj[hub]) {
if (belt === arrived) continue;
// [5] A neighbour that is already seen is reached by a second belt: a loop.
if (seen[neighbour]) return true;
// [6] A new neighbour is marked now and waits on the stack, so it is pushed once.
seen[neighbour] = true;
stack.push([neighbour, belt]);
}
}
}
// [7] No walk found a second belt to a seen hub: no loop.
return false;
}On the six-hub map this returns true. On the tree with belts 0-1, 0-2, 2-3, 2-4 and 4-5 it returns false. The colouring uses a queue, and gives each new hub the colour 1 - colour[hub].
from collections import deque
def can_two_colour(n, edges):
# [1] Build the neighbour lists: a belt joins two hubs both ways.
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
colour = [-1] * n
# [2] Start a walk from every hub with no colour yet, and give it colour 0.
for start in range(n):
if colour[start] != -1:
continue
colour[start] = 0
queue = deque([start])
while queue:
# [3] Take the next hub from the queue.
hub = queue.popleft()
# [4] Look at every hub it shares a belt with.
for other in adj[hub]:
# [5] A neighbour with the same colour breaks the rule.
if colour[other] == colour[hub]:
return False
# [6] A neighbour with no colour gets the other colour and joins the queue.
if colour[other] == -1:
colour[other] = 1 - colour[hub]
queue.append(other)
# [7] No belt joined two hubs of one colour.
return Truepublic boolean canTwoColour(int n, int[][] edges) {
// [1] Build the neighbour lists: a belt joins two hubs both ways.
java.util.List<Integer>[] adj = new java.util.List[n];
for (int i = 0; i < n; i++) adj[i] = new java.util.ArrayList<>();
for (int[] e : edges) {
adj[e[0]].add(e[1]);
adj[e[1]].add(e[0]);
}
int[] colour = new int[n];
java.util.Arrays.fill(colour, -1);
// [2] Start a walk from every hub with no colour yet, and give it colour 0.
for (int start = 0; start < n; start++) {
if (colour[start] != -1) continue;
colour[start] = 0;
java.util.ArrayDeque<Integer> queue = new java.util.ArrayDeque<>();
queue.add(start);
while (!queue.isEmpty()) {
// [3] Take the next hub from the queue.
int hub = queue.poll();
// [4] Look at every hub it shares a belt with.
for (int other : adj[hub]) {
// [5] A neighbour with the same colour breaks the rule.
if (colour[other] == colour[hub]) return false;
// [6] A neighbour with no colour gets the other colour and joins the queue.
if (colour[other] == -1) {
colour[other] = 1 - colour[hub];
queue.add(other);
}
}
}
}
// [7] No belt joined two hubs of one colour.
return true;
}bool canTwoColour(int n, vector<vector<int>> edges) {
// [1] Build the neighbour lists: a belt joins two hubs both ways.
vector<vector<int>> adj(n);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
vector<int> colour(n, -1);
// [2] Start a walk from every hub with no colour yet, and give it colour 0.
for (int start = 0; start < n; start++) {
if (colour[start] != -1) continue;
colour[start] = 0;
queue<int> pending;
pending.push(start);
while (!pending.empty()) {
// [3] Take the next hub from the queue.
int hub = pending.front();
pending.pop();
// [4] Look at every hub it shares a belt with.
for (int other : adj[hub]) {
// [5] A neighbour with the same colour breaks the rule.
if (colour[other] == colour[hub]) return false;
// [6] A neighbour with no colour gets the other colour and joins the queue.
if (colour[other] == -1) {
colour[other] = 1 - colour[hub];
pending.push(other);
}
}
}
}
// [7] No belt joined two hubs of one colour.
return true;
}function canTwoColour(n, edges) {
// [1] Build the neighbour lists: a belt joins two hubs both ways.
const adj = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
adj[a].push(b);
adj[b].push(a);
}
const colour = new Array(n).fill(-1);
// [2] Start a walk from every hub with no colour yet, and give it colour 0.
for (let start = 0; start < n; start++) {
if (colour[start] !== -1) continue;
colour[start] = 0;
const queue = [start];
for (let head = 0; head < queue.length; head++) {
// [3] Take the next hub from the queue.
const hub = queue[head];
// [4] Look at every hub it shares a belt with.
for (const other of adj[hub]) {
// [5] A neighbour with the same colour breaks the rule.
if (colour[other] === colour[hub]) return false;
// [6] A neighbour with no colour gets the other colour and joins the queue.
if (colour[other] === -1) {
colour[other] = 1 - colour[hub];
queue.push(other);
}
}
}
}
// [7] No belt joined two hubs of one colour.
return true;
}The one-way walk keeps its path in a list and counts the belts tried for each hub. It has no recursion, so a chain of 100,000 hubs is safe.
def has_directed_loop(n, edges):
# [1] Build the lists of one-way belts out of each hub. A mark is 0 new, 1 on the current path or 2 finished.
out = [[] for _ in range(n)]
for a, b in edges:
out[a].append(b)
mark = [0] * n
taken = [0] * n
# [2] Start a walk from every hub not visited yet.
for start in range(n):
if mark[start] != 0:
continue
mark[start] = 1
path = [start]
while path:
# [3] Look at the hub at the end of the path.
hub = path[-1]
if taken[hub] < len(out[hub]):
# [4] It still has a belt to try: take the next one.
nxt = out[hub][taken[hub]]
taken[hub] += 1
# [5] A belt to a hub on the path closes a loop.
if mark[nxt] == 1:
return True
# [6] A new hub is marked as on the path and extends it.
if mark[nxt] == 0:
mark[nxt] = 1
path.append(nxt)
else:
# [7] No belts left: the hub is finished and leaves the path.
mark[hub] = 2
path.pop()
# [8] No walk found a belt back to its own path.
return Falsepublic boolean hasDirectedLoop(int n, int[][] edges) {
// [1] Build the lists of one-way belts out of each hub. A mark is 0 new, 1 on the current path or 2 finished.
java.util.List<Integer>[] out = new java.util.List[n];
for (int i = 0; i < n; i++) out[i] = new java.util.ArrayList<>();
for (int[] e : edges) out[e[0]].add(e[1]);
int[] mark = new int[n];
int[] taken = new int[n];
// [2] Start a walk from every hub not visited yet.
for (int start = 0; start < n; start++) {
if (mark[start] != 0) continue;
mark[start] = 1;
java.util.ArrayDeque<Integer> path = new java.util.ArrayDeque<>();
path.push(start);
while (!path.isEmpty()) {
// [3] Look at the hub at the end of the path.
int hub = path.peek();
if (taken[hub] < out[hub].size()) {
// [4] It still has a belt to try: take the next one.
int nxt = out[hub].get(taken[hub]);
taken[hub]++;
// [5] A belt to a hub on the path closes a loop.
if (mark[nxt] == 1) return true;
// [6] A new hub is marked as on the path and extends it.
if (mark[nxt] == 0) {
mark[nxt] = 1;
path.push(nxt);
}
} else {
// [7] No belts left: the hub is finished and leaves the path.
mark[hub] = 2;
path.pop();
}
}
}
// [8] No walk found a belt back to its own path.
return false;
}bool hasDirectedLoop(int n, vector<vector<int>> edges) {
// [1] Build the lists of one-way belts out of each hub. A mark is 0 new, 1 on the current path or 2 finished.
vector<vector<int>> out(n);
for (auto& e : edges) out[e[0]].push_back(e[1]);
vector<int> mark(n, 0);
vector<int> taken(n, 0);
// [2] Start a walk from every hub not visited yet.
for (int start = 0; start < n; start++) {
if (mark[start] != 0) continue;
mark[start] = 1;
vector<int> path = {start};
while (!path.empty()) {
// [3] Look at the hub at the end of the path.
int hub = path.back();
if (taken[hub] < (int)out[hub].size()) {
// [4] It still has a belt to try: take the next one.
int nxt = out[hub][taken[hub]];
taken[hub]++;
// [5] A belt to a hub on the path closes a loop.
if (mark[nxt] == 1) return true;
// [6] A new hub is marked as on the path and extends it.
if (mark[nxt] == 0) {
mark[nxt] = 1;
path.push_back(nxt);
}
} else {
// [7] No belts left: the hub is finished and leaves the path.
mark[hub] = 2;
path.pop_back();
}
}
}
// [8] No walk found a belt back to its own path.
return false;
}function hasDirectedLoop(n, edges) {
// [1] Build the lists of one-way belts out of each hub. A mark is 0 new, 1 on the current path or 2 finished.
const out = Array.from({ length: n }, () => []);
for (const [a, b] of edges) out[a].push(b);
const mark = new Array(n).fill(0);
const taken = new Array(n).fill(0);
// [2] Start a walk from every hub not visited yet.
for (let start = 0; start < n; start++) {
if (mark[start] !== 0) continue;
mark[start] = 1;
const path = [start];
while (path.length > 0) {
// [3] Look at the hub at the end of the path.
const hub = path[path.length - 1];
if (taken[hub] < out[hub].length) {
// [4] It still has a belt to try: take the next one.
const nxt = out[hub][taken[hub]];
taken[hub]++;
// [5] A belt to a hub on the path closes a loop.
if (mark[nxt] === 1) return true;
// [6] A new hub is marked as on the path and extends it.
if (mark[nxt] === 0) {
mark[nxt] = 1;
path.push(nxt);
}
} else {
// [7] No belts left: the hub is finished and leaves the path.
mark[hub] = 2;
path.pop();
}
}
}
// [8] No walk found a belt back to its own path.
return false;
}A recursive version is shorter, but it fails on a long chain. In Python, a recursive walk over a chain of 5,000 hubs stops with a RecursionError, because the default limit is 1,000 calls. The version above handles the same chain.
Exercise · Put it in order: Mark the path, then mark it finished. Arrange the lines into a walk over one-way belts that returns true when a cycle is reachable from the hub. A mark is 0 for new, 1 for on the path and 2 for finished.
def has_cycle_from(out, mark, hub):
mark[hub] = 1
for nxt in out[hub]:
if mark[nxt] == 1:
return True
if mark[nxt] == 0 and has_cycle_from(out, mark, nxt):
return True
mark[hub] = 2
return False
if mark[nxt] != 0:Now write the checks for the layout tool. The lab has three functions. Each test gives your function a number of hubs and a list of belts, and checks the answer.
has_loop(n, edges): true when the two-way belts contain a cycle. Two belts between one pair of hubs are a cycle.can_two_colour(n, edges): true when every hub can get colour 0 or 1 with no belt joining two hubs of one colour.has_directed_loop(n, edges): true when the one-way belts, each from a to b, contain a cycle. A belt from a hub to itself is a cycle.Three rules keep them correct:
has_loop, skip the arrival belt by its number, not the hub it came from.has_directed_loop, tell a hub on the path from a finished hub. Only the first closes a cycle.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | Two-way loop walk | Two colours | One-way marks | Counting (Kahn) |
|---|---|---|---|---|
| Time | O(n + m): each hub is pushed once and each belt looked at twice | O(n + m): the same | O(n + m): each belt is tried once | O(n + m): each hub settles once and each belt is removed once |
| Memory | O(n + m) for the lists, the marks and the stack | O(n + m) for the lists, the colours and the queue | O(n + m) for the lists, the marks and the path | O(n + m) for the lists, the counts and the queue |
| Answers | Whether a cycle exists | Whether two colours work | Whether a cycle exists, and which hubs finish | Whether a cycle exists, and an order when none |
| Fails on | A skipped belt number | An odd cycle | A finished hub read as a path hub | A settled count below n |
For 100,000 hubs and 100,000 belts, each check takes a few hundred thousand steps. None of them is ever the slow part of a layout tool.
Use these walks when you have a whole map and one yes-or-no question about it. Examples are: is there a cycle, is it a tree, or can it be split into two colours? Each takes one pass over the hubs and belts.
Use the counting version for one-way belts when you want a settled count and do not need recursion. Use the marked path when you also want to know which hubs reach a cycle, as in find-the-safe-states.
Use Topological sort (A3) when you need more than a yes or no. If the one-way belts have no cycle, topological sort also gives an order that respects every belt, such as a build order. It is the same count, kept as a list.
Use Union-find (A4) when belts arrive one at a time and you ask after each one. A belt whose two hubs are already in one group closes a cycle, and union-find answers in almost constant time without walking the map again.
Writing if seen[neighbour]: return True without the arrival belt makes the hub you came from look like a cycle. On the tree with belts 0-1, 0-2, 2-3, 2-4 and 4-5, that code returns true, and the correct answer is false. Skip the belt you arrived by.
Without the arrival belt check, the hub you came from looks like a second route, and a map with no cycle is called a cycle.
In one-way belts, if seen[next]: return True calls a finished hub a cycle. On the diamond with belts 0 to 1, 0 to 2, 1 to 3 and 2 to 3, that code returns true, and the correct answer is false. Keep a separate mark for the hubs on the path.
If the colouring starts at hub 0 only, a separate part is never coloured. On 5 hubs with belts 0-1, 2-3, 3-4 and 4-2, a walk from hub 0 returns true. But hubs 2, 3 and 4 form a triangle, so the correct answer is false. Start from every uncoloured hub.
The rule len(edges) >= n sounds right, because a tree has n - 1 belts. But with 7 hubs and belts 0-1, 2-3, 3-4, 4-2 and 5-6, there are 5 belts and a cycle, and 5 >= 7 is false. The count must use the number of parts: a cycle exists when the belts number more than n - c.
A recursive walk such as def go(v): ... go(u) is short, but a chain of 5,000 hubs stops it with a RecursionError in Python. Use a stack or a path list, as in the templates above.
n - 1 belts. Start a walk in every part, because a map can have several components.Explain the three checks in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Cycles in two-way belts
Q1/5 Which description is a cycle?
Answer: B
A cycle returns to its start without using a belt twice. Two belts between the same pair of hubs make a cycle of two.
Q2/5 A walk with a stack reaches a hub that is already marked, by a belt that is not the belt it arrived by. What does that show?
Answer: C
The marked hub was reached by one belt earlier, and now by a second one. Two routes to one hub close a cycle.
Q3/5 Why does the loop check skip the arrival belt by its number, and not the hub it came from?
Answer: B
Each belt has its own number, so the second of two parallel belts is a different belt from the arrival belt, and the walk sees the cycle.
Q4/5 A map has 9 hubs in 3 separate parts and no cycle. How many belts does it have?
Answer: C
A part with k hubs and no cycle has k - 1 belts, so the whole map has n - c = 9 - 3 = 6 belts.
Q5/5 A walk from hub 0 finds no cycle, but the map has 2 parts. Why can a cycle still exist?
Answer: B
A walk reaches one part. The code must start a new walk from every hub that is still unseen.
Checkpoint · Colours, trees and one-way belts
Q1/5 Which map can be given two colours, so that no belt joins two hubs of one colour?
Answer: C
The colour flips at every belt. A loop with an even number of belts returns to the start with the same colour. A loop of three, five or seven does not.
Q2/5 You colour a map from hub 0 only, and no clash appears. Which map still breaks the rule?
Answer: B
A walk reaches only hub 0's part. A triangle in another part is never coloured, so its clash is missed.
Q3/5 A map has 6 hubs and 5 belts, and it contains a loop of three hubs. What must also be true?
Answer: C
A connected map with n - 1 belts is a tree, which has no cycle. So a map with a cycle and n - 1 belts cannot be connected.
Q4/5 In a walk over one-way belts, a belt leads to a hub that is finished. What does the walk do?
Answer: B
Only a hub on the current path closes a cycle. A finished hub was left after all its belts were tried, so the belt only joins a second route.
Q5/5 You need to know whether one-way belts have a cycle and, when they do not, a valid order that respects every belt. Belts do not change. Which tool fits?
Answer: C
Topological sort counts what each hub waits for. It reports a cycle when some hubs are never settled, and gives the order when all are. Union-find fits belts that arrive one at a time.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.