7 routes42 sections324 units

Unit 3.3 · about 4 h

106 / 324

DFS, cycle detection and bipartite testing

DFS supplies the recursion structure BFS cannot: finish times, edge classification and back-edge witnesses. Cycles and two-coloring are its first two customers.

  • derive
  • implement

You can now

  • Implement recursive and iterative DFS with pre-order, post-order and on-stack hooks, and derive the \(\Theta(V + E)\) bound.
  • Detect directed cycles with three-color DFS and undirected cycles with parent-tracking DFS, and exhibit the false positive each wrong pairing produces.
  • Test bipartiteness with two-color BFS or DFS and explain the odd-cycle obstruction.

Covers

  • DFS state, timestamps and recursive versus iterative traversal
  • Cycle detection in directed and undirected graphs
  • Bipartite testing and two-color invariants

Study, in this order

4 steps

  1. Depth-first search
    DSA Handbook - graphs

    The recursive form; Three flavors: pre-order, post-order, on-stack; Worked example: LC 130 Surrounded Regions; Two pitfalls that bite

  2. Cycle detection in graphs
    DSA Handbook - graphs

    Why the obvious approach reports cycles that are not there (diamond); The other half: undirected graphs need a parent argument; Worked example: LC 1361

    Depth · Skim the Floyd tortoise-and-hare pointer; it belongs to linked lists, not graphs.

  3. Bipartite check
    DSA Handbook - graphs

    Why the obvious approach wastes most of its work; The pattern (LC 785); Worked example on a 4-cycle and a triangle

  4. Depth-first search through cycle detection
    Algorithms - graph chapters

    Sections 6.1 Preorder and Postorder (with Classifying Vertices and Edges) and 6.2 Detecting Cycles (printed pp. 227-232)

Focus on

  • Mark before recursing, on entry. Recursing first lets the neighbor immediately recurse back, which loops until RecursionError.
  • GRAY means on the current stack; BLACK means finished. The diamond edge into a BLACK vertex is a benign forward edge; only a GRAY neighbor is a back edge and a cycle witness.
  • Undirected DFS needs one boolean plus the parent argument: the neighbor you arrived from does not count. Three colors are unnecessary there because undirected DFS has no forward or cross edges.
  • Bipartite colors are 1 and -1 with 0 for unvisited, flipped by negation across each edge, inside an outer loop over components. A same-color edge is the odd-cycle witness.

Reproduce closed-book

From a blank file with the course Python (3.13.14), run three-color DFS on the diamond [(0,1),(0,2),(1,3),(2,3)] and report no cycle, and on [(0,1),(1,2),(2,0)] report a cycle. Then run two-color BFS on [[1,3],[0,2],[1,3],[0,2]] (True) and on [[1,2],[0,2],[0,1]] (False).

Traps

  • Two-color directed DFS: the diamond reports a cycle because one visited bit conflates on-stack with finished. The fix is the third color, not a second visited set.
  • Parentless undirected DFS: a single edge reports a cycle because each endpoint sees the other as visited. The fix is the parent argument, not more colors.
  • Recursive DFS on deep grids or chains: CPython caps the stack at 1000 frames by default (check with sys.getrecursionlimit), so a snake region or a 2000-chain crashes. Set the limit explicitly or ship the iterative form.

Practice

LeetCode 130: Surrounded Regions

The two listed examples (\(4 \times 4\) board with two interior O cells flipping; single-cell board)

Pre-order DFS from every border O, marking first and recursing second. After-attempt reference is the DSA Handbook 8.2 worked example.

LeetCode 785: Is Graph Bipartite?

Examples 1 (triangle inside, False) and 2 (4-cycle, True)

Two-color BFS with the outer component loop. After-attempt reference is the DSA Handbook 8.7 worked example.

Self-test

  1. Prove a directed graph is acyclic iff DFS finds no back edge.

  2. Prove a graph is bipartite iff it has no odd cycle.

  3. Why does the bipartite outer loop cost nothing on connected graphs?

  4. LC 130 floods from the border instead of testing each region. Why is the inversion sound?

Completion criterion

Stop when

Your blank-file script prints the four reproduce verdicts (no cycle, cycle, True, False), and LC 130 plus LC 785 pass with the visited discipline stated up front.

Mark passed, then open 3.4 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • DSA Handbook - graphs
    Handbook Academyprimarycourse
    Study all of Part 8 in order. For each algorithm, write the representation, invariant, forbidden input assumptions and independently checkable output before reading the implementation.
  • Algorithms - graph chapters
    Jeff Ericksonrequiredtheory
    Use the basic graph, depth-first search, minimum spanning tree, shortest path and flow chapters, and lecture note 11 Disjoint Sets for union-find, for correctness proofs and counterexamples to tempting wrong algorithms.

Also in this section

  • AlgoMaster DSA - graph slice
    AlgoMasterrequiredpractice
    Attempt Number of Islands, Course Schedule II and Network Delay Time cold. They cover traversal, dependency modeling and weighted shortest paths; add one narrative problem only if graph modeling remains weak.
  • Hypothesis - generated graph tests
    Hypothesissupportpractice
    Generate small sparse, dense, disconnected, cyclic, parallel-edge and weighted graphs. Compare optimized results with exhaustive or deliberately simple references and retain shrunk failures.
  • NeetCode - unseen graph problems
    NeetCodeoptionalassessment
    Use two unseen story problems without graph tags. Grade the model, assumptions, certificate and tests as well as the final answer.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels