Skip to the workspace
Pebellslearn by building
Graph Structure & Decomposition  ›  Lesson

Finding the Cycle

Cycle Detection 28 minThree colours: an edge back into grey is the loop

dsa / Finding the Cycle

Explore each scene at your own pace.

01 · Visited is not enough

Visited is not enough

Finding the Cycle

Definition
Cycle detection in a directed graph uses depth-first search with three colours: white for unvisited, grey for on the current path, black for finished. An edge into a grey node is a back edge, and it proves a cycle exists.
In plain words
Walking through a maze, you trail a string behind you. If a corridor leads back to a spot your string already passes through, you have walked in a circle. Spots you fully explored and left are safe to meet again.

In short: colour every depot white, grey or black as DFS runs: grey means "on the path you're walking right now", black means "finished, nothing below it can lead back to you". An arrow into a grey depot is a back edge, and it closes a loop — the loop is exactly the grey path from that depot down to where you stand. An arrow into a black depot never is a loop, because anything reachable from a black depot was already explored while it was still grey.

Five depots: hub and north and east and south are grey, yard is black, with a dashed red back edge from south to north closing the loop north, east, south

When a Meridian depot fills up, it forwards its overflow to another depot. Each depot manager sets their own rule, and nobody looks at all of them together. So one night north forwards to east, east forwards to south, south forwards back to north, and a van of parcels drives in a circle until morning.

Kahn's algorithm from the last lesson could tell you that some loop exists, because loops are what it leaves behind. The operations team wants more than that: which depots, in what order, so someone can phone the right manager. This lesson finds the loop itself, using depth-first search and three colours.

Visited is not enough

The first idea is to run DFS and shout "loop!" the moment you reach a depot you've already visited. Try it on four depots where two routes happen to meet:

What does this print?
after = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
visited = set()

def visit(depot):
    if depot in visited:
        return True                # "seen it before, must be a loop"
    visited.add(depot)
    return any(visit(nxt) for nxt in after[depot])

print(visit("a"))

Reaching an old depot tells you two routes meet. It doesn't tell you there's a way back. For that you need to know whether the old depot is still on the path you are walking right now.

Scene 1 of 10
Project context and further resources
You're building a piece ofMeridian — the network model
This piece — find_loop(): Finds a chain of overflow rules that would send parcels round in a circle forever.
Scenario When a Meridian depot fills up, it forwards overflow to another depot, and each depot manager sets their own rule. Nobody sees the whole picture, so sooner or later north forwards to east, east to south, and south back to north, and a van of parcels drives in circles all night. The loop detector finds that circle before the vans do.
find_loop.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
find_loop(depots, forwards) → listOne loop of overflow rules, starting at its smallest depot, or [] if parcels can never circle.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.