~/ learn/ comp-372/ cards/ Depth-first search & edge classification
1 of 6

Type the DFS edge-colour test that detects a cycle

Type the DFS edge-colour test that detects a cycle

Answer

if color[v] == WHITE: visit(v) # tree edge elif color[v] == GRAY: has_back_edge = True # back edge -> cycle

White neighbour = tree edge (recurse). Gray neighbour = back edge, meaning v is an ancestor of u, so the graph has a cycle.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/7fcd80fc-f820-47ce-85a1-c27b9665f9a2/flashcard utf-8 LF