DFS, BFS & Graph Traversal · 15 min · free lesson

Challenge: Graph DFS

Edges are undirected, and vertices run from 0 to the largest endpoint. Return recursive DFS order from node 0 using ascending neighbors.

Core idea

The required traversal uses ascending neighbors. Edges are undirected, and vertices run from 0 to the largest endpoint. Return recursive DFS order from node 0 using ascending neighbors.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Explore one branch fully while marking nodes before following outgoing edges.

O(V+E) traversal; neighbor sorting adds sum(deg log deg) · O(V+E) copied graph31 execution steps
main · before line 27Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputedges=(0,2),(0,1)

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 27
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn dfs_order(graph: &[Vec<usize>], start: usize) -> Vec<usize> {
    fn visit(v: usize, g: &[Vec<usize>], seen: &mut [bool], out: &mut Vec<usize>) {
        seen[v] = true;
        out.push(v);
        for &u in &g[v] {
            if !seen[u] {
                visit(u, g, seen, out);
            }
        }
    }
    let mut sorted = graph.to_vec();
    for ns in &mut sorted {
        ns.sort_unstable();
    }
    let mut out = Vec::new();
    visit(start, &sorted, &mut vec![false; graph.len()], &mut out);
    out
}
 
fn main() {
    let result = csv(dfs_order(&[vec![1, 2], vec![0], vec![0]], 0));
    println!("{result}");
}

Try your own version

Change the independent fixture `edges=(0,2),(0,1)` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `edges=(0,1),(0,2),(1,3),(2,4)`.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line. Borrowed or moved values are hidden when they cannot be inspected safely.
Five-panel DFS, BFS & Graph Traversal infographic; panel 2 illustrates Graph Dfs.
Graph Dfs: follow panel 2 to see the operation, then trace this lesson's example.

Understand it

The required traversal uses ascending neighbors. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input edges=(0,2),(0,1), the worked program returns 0,1,2. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input edges=(0,1),(0,2),(1,3),(2,4); predict that result before opening the answer reveal. The precise contract is: Edges are undirected, and vertices run from 0 to the largest endpoint. Return recursive DFS order from node 0 using ascending neighbors.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Edges are undirected, and vertices run from 0 to the largest endpoint. Return recursive DFS order from node 0 using ascending neighbors. On input edges=(0,1),(0,2),(1,3),(2,4), predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Explore one branch fully while marking nodes before following outgoing edges. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. A graph method needs an explicit vertex-and-edge representation. For traversal, define when a vertex becomes seen: on insertion into the frontier or on removal. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(V+E) traversal; neighbor sorting adds sum(deg log deg) · O(V+E) copied graph; explain which operation dominates it and how many times the input can trigger that operation. Test an isolated vertex, a cycle, duplicate edges, and a graph whose starting vertex reaches only one component. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

The pattern

Explore one branch fully while marking nodes before following outgoing edges.

When to use it: reachability, components, path existence

Complexity: O(V+E) traversal; neighbor sorting adds sum(deg log deg) · O(V+E) copied graph

Input: edges=(0,1),(0,2),(1,3),(2,4)

Read the code

fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn dfs_order(graph: &[Vec<usize>], start: usize) -> Vec<usize> {
    fn visit(v: usize, g: &[Vec<usize>], seen: &mut [bool], out: &mut Vec<usize>) {
        seen[v] = true;
        out.push(v);
        for &u in &g[v] {
            if !seen[u] {
                visit(u, g, seen, out);
            }
        }
    }
    let mut sorted = graph.to_vec();
    for ns in &mut sorted {
        ns.sort_unstable();
    }
    let mut out = Vec::new();
    visit(start, &sorted, &mut vec![false; graph.len()], &mut out);
    out
}

fn main() {
    let result = csv(dfs_order(&[vec![1, 2], vec![0], vec![0]], 0));
    println!("{result}");
}

Complete std-only graph-dfs program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // Edges are undirected, and vertices run from 0 to the largest endpoint. Return recursive DFS order from node 0 using ascending neighbors.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement graph-dfs")
}

Try it

Edges are undirected, and vertices run from 0 to the largest endpoint. Return recursive DFS order from node 0 using ascending neighbors.

What success looks like: The private harness prints PASS graph-dfs. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for graph-dfs: with input edges=(0,1),(1,2),(2,0), what result should solve return?

Reveal the answer
  1. 0,1,2
  2. 1,2
  3. 1,1,2

For this input the result is 0,1,2. The required traversal uses ascending neighbors. Compare this independent fixture with the worked trace: Starting at 0 with neighbors 1 and 2, visit 1 and its descendant 3 before returning to explore 2 and 4. Output is 0,1,3,2,4. Mark a node before recursing so a cycle does not revisit it.

Go deeper

Common misconception: “DFS correctness always requires sorted edges”

The required traversal uses ascending neighbors. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: The required traversal uses ascending neighbors. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses edges=(0,2),(0,1) and computes 0,1,2. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For edges=(0,1),(1,2),(2,0), the independently calculated result is 0,1,2. The complexity discussion uses O(V+E) traversal; neighbor sorting adds sum(deg log deg) · O(V+E) copied graph. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture edges=(0,2),(0,1) in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge edges=(0,1),(0,2),(1,3),(2,4).

Connections

  • Graph DFS: When to Use It: reachability, components, path existence
  • Graph BFS: Mental Model: Process the frontier in queue order so first discovery has minimum edge count.
Reveal the Algorithm Atlas answer

0,1,3,2,4

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Challenge: Graph DFS (courseId "algorithms", lessonId "algorithm.graph-dfs.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.graph-dfs.challenge
Goal: The required traversal uses ascending neighbors. Edges are undirected, and vertices run from 0 to the largest endpoint. Return recursive DFS order from node 0 using ascending neighbors.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.graph-dfs.challenge) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.