algosgraphs

dfs

go as deep as you can down one path, then back up and try the next.

report a mistake
.md

start at a vertex and follow the first neighbor you haven't seen, again and again. when a vertex has none left, back up one and try its next. the vertices on the way down sit on a stack, and the stack is the path you took.

time
O(n + m) each vertex visited once, each list entry looked at once
space
O(n) a seen flag per vertex, and the stack
topo sort
one pass the finish order reversed. a cycle is an edge to a vertex still on the stack
stack depth
up to n a path puts every vertex on the stack at once. recursive, that's n calls deep
shortest paths
no it reaches a vertex by whichever path it dives down first. bfs finds the shortest
reach for it
  • is there a path, and which vertices can be reached
  • connected components, islands in a grid
  • a cycle in a directed graph
  • a topological order, tasks and what each one needs first
  • backtracking, dfs over choices instead of vertices
  • strongly connected components, bridges, cut vertices
on this page
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. the back edge, up close
  6. complexity
  7. implementations
  8. pitfalls
  9. variants
  10. practice
  11. how real libraries do it
  12. sources

dfs, depth-first search, starts at a vertex and goes as deep as it can. it follows the first neighbor it hasn’t seen, then that vertex’s first new neighbor, and so on, and when a vertex has no new neighbors left it backs up one step and tries the next. the vertices on the way down sit on a stack, so the stack is always the path from the start to where the search is. every vertex it can reach is visited once and every edge is looked at once per end: O(n + m). bfs on the same graph fans out a level at a time. dfs dives.

the idea

the graph from the graphs page: 6 vertices, 7 edges, and each vertex’s neighbors in a list, smallest first. start at 0: mark it seen and push it. the stack reads 0.

an animation in five steps over a graph of 6 vertices, 0 to 5, with 7 edges, and under it a strip for the stack and a readout of the order so far with counts of vertices visited and list entries looked at. first 0 gets a white ring: it's the top of the stack, and the stack reads 0. then the search looks at 0's first neighbor, 1. the edge is white while it's looked at and turns cyan as the search follows it, 1 takes the white ring as the new top, and 0 under it keeps a cyan ring. then it dives on, 1 to 2, 2 to 4, 4 to 5 and 5 to 3, each new vertex white as it's pushed and each edge it follows cyan, while an edge it looks at that leads to a vertex seen already, like 2 to 0, dims. the stack reads 0, 1, 2, 4, 5, 3, six deep. then the vertices pop in the order 3, 5, 4, 2, 1, 0, each filled in white as it's done, until the stack is empty. last, the order reads 0, 1, 2, 4, 5, 3, with 6 vertices visited and 14 entries looked at, and under it bfs's order for the same graph, 0, 1, 2, 3, 4, 5. the five cyan edges are the tree the search followed, and the other two are dim.

watch it run

step through the search from any vertex: tap one to start there. or switch to topo sort, on a dag of the tasks in building a house. the top of the stack has a white ring, the rest of the stack a cyan one, and a vertex that has popped is filled in. an edge is white while it’s looked at, cyan once the search follows it, and dim once it has led to a vertex seen already. each entry on the stack is a pair, a vertex and the index of its next neighbor, and the pseudocode follows along.

tap a vertex to start there
012345
[0, 0]
0

start at 0: visit it and push [0, 0]

visited
1
looked at
0
deepest
1
step
1 of 27
pseudocode
dfs(adj, src):  # the vertices src reaches, in the order they're first seen  seen = [false] * len(adj)  order = []  stack = []  # pairs: a vertex, and the index of its next neighbor to look at  visit(src)  # seen[v] = true, order.append(v), stack.append([v, 0])  while stack:    u, i = stack[-1]    if i == len(adj[u]):  # no neighbors left: u is done      stack.pop()      continue    stack[-1][1] = i + 1  # move on, whatever v turns out to be    v = adj[u][i]    if not seen[v]: visit(v)  # new: go deeper  return order topo_sort(adj):  # adj[u] holds the edges u -> v. none if there's a cycle  state = [new] * len(adj)  # new, open (on the stack) or done  finished = []  for s in 0 .. len(adj) - 1:    if state[s] != new: continue    state[s] = open; stack = [[s, 0]]    while stack:      u, i = stack[-1]      if i == len(adj[u]):  # every edge out of u leads to a done vertex        state[u] = done; finished.append(u)        stack.pop()        continue      stack[-1][1] = i + 1      v = adj[u][i]      if state[v] == open: return none  # a back edge: a cycle      if state[v] == new: state[v] = open; stack.append([v, 0])  return reversed(finished)

an interactive stepper with two modes. search: the graph of 6 vertices from the movie, from a start you pick by tapping a vertex, 0 to begin with. each step looks at the next entry of the top vertex's list, visits a new vertex, or pops one. the top of the stack has a white ring, the rest of the stack a cyan ring, and a vertex that has popped is filled in. an edge is white while it's looked at, cyan once the search follows it, and dim once it has led to a vertex seen already. under the graph, one strip shows the stack, bottom to top, each entry a vertex and the index of its next neighbor, and another the order so far, with counts of vertices visited, entries looked at, how deep the stack has been, and the step, and the matching pseudocode line is highlighted. from 0 it visits 0, 1, 2, 4, 5, 3 in 27 steps, 14 of them looks, and the stack reaches 6 deep. topo sort: a dag of 8 tasks in building a house, numbered 0 to 7, foundation, framing, roof, plumbing, wiring, drywall, paint and floors, with an arrow from each task to the ones that wait for it. the same stepping, with a finished list that grows as vertices pop, 6, 7, 5, 2, 3, 4, 1, 0, and at the end the order, that list reversed, 0, 1, 4, 3, 2, 5, 7, 6, in 26 steps with 9 entries looked at. a switch adds an edge from floors to framing, and the run then stops after 14 steps: 7 to 1 meets 1 while it's still open, the edge turns amber, and that's a cycle.

try it

dfs is one rule, applied over and over: the first new neighbor of the top, or pop. apply it. every list here is in number order, so the smallest new neighbor goes first.

dfs from 0 has visited 0, 1, 2. which vertex does it visit next?

every list is in number order: the smallest neighbor goes first.

012345
012
012

tap a vertex, or none.

0 / 0 right

a practice exercise on small graphs, where every list is in number order, so the smallest new neighbor goes first. some questions show a search partway through, with the vertices it has visited, the stack with its top in white, and the edges it has followed in cyan, and ask which vertex it visits next, answered by tapping a vertex, or none when everything it can reach is seen. others fill in every vertex seen so far and ask what's on the stack, bottom to top, or ask for the whole order from a start, with bfs's order among the choices. the rest show a small dag with arrows and ask which of three orders is a valid topological order: the other two each have an edge pointing backward.

pseudocode

pseudocode
dfs(adj, src):  # the vertices src reaches, in the order they're first seen
  seen = [false] * len(adj)
  order = []
  stack = []  # pairs: a vertex, and the index of its next neighbor to look at
  visit(src)  # seen[v] = true, order.append(v), stack.append([v, 0])
  while stack:
    u, i = stack[-1]
    if i == len(adj[u]):  # no neighbors left: u is done
      stack.pop()
      continue
    stack[-1][1] = i + 1  # move on, whatever v turns out to be
    v = adj[u][i]
    if not seen[v]: visit(v)  # new: go deeper
  return order

topo_sort(adj):  # adj[u] holds the edges u -> v. none if there's a cycle
  state = [new] * len(adj)  # new, open (on the stack) or done
  finished = []
  for s in 0 .. len(adj) - 1:
    if state[s] != new: continue
    state[s] = open; stack = [[s, 0]]
    while stack:
      u, i = stack[-1]
      if i == len(adj[u]):  # every edge out of u leads to a done vertex
        state[u] = done; finished.append(u)
        stack.pop()
        continue
      stack[-1][1] = i + 1
      v = adj[u][i]
      if state[v] == open: return none  # a back edge: a cycle
      if state[v] == new: state[v] = open; stack.append([v, 0])
  return reversed(finished)

the pair on the stack is the whole trick. a recursive dfs keeps how far it got through u’s list in the call frame. here it sits in the pair, so popping back to u carries on from the next neighbor, and the order comes out the same, visit for visit. seen[v] is set when v is pushed, not when it pops, so an edge to a vertex that’s on the stack is skipped too. topo_sort keeps those two apart: open means on the stack, done means popped, and the difference is how it finds a cycle.

the back edge, up close

floors before framing, 7 → 1, added

01234567
01257

the search meets 7 → 1 while 1 is still open. the stack from 1 up, 1, 2, 5, 7, is a path from 1 down to 7, and the edge closes it into a loop: no order can put 1 both before and after 7.

as planned: each task's place in the finish order

012345671st2nd3rd4th5th6th7th8th
finished
6, 7, 5, 2, 3, 4, 1, 0
reversed
0, 1, 4, 3, 2, 5, 7, 6

every edge points from a later finish to an earlier one, so the finish order reversed has every edge pointing forward.

0 foundation, 1 framing, 2 roof, 3 plumbing, 4 wiring, 5 drywall, 6 paint, 7 floors

  • new: not reached yet
  • open: on the stack. the search is somewhere under it and will come back through it
  • the top: open too, and where the search is
  • done: popped, after everything it points to
  • a cyan edge: the search followed it to a new vertex
  • an amber edge: it leads to an open vertex, so there's a cycle

two drawings of the dag of tasks. in the first, an edge from floors to framing, 7 to 1, is added, and the picture is the moment the topological sort reaches it. 0, 1, 2 and 5 have cyan rings, open on the stack under 7, which has the white ring of the top. 6 is filled in, done, and 3 and 4 are plain, not reached. the edges 0 to 1, 1 to 2, 2 to 5, 5 to 6 and 5 to 7 are cyan, the ones the search followed, and 7 to 1 is amber. a strip reads the stack, 0, 1, 2, 5, 7, and the text under it says the part from 1 up, 1, 2, 5, 7, is a path from 1 down to 7, which the edge closes into a loop, so no order can exist. in the second, the dag as planned, every task is filled in and marked with its place in the finish order: 6 1st, 7 2nd, 5 3rd, 2 4th, 3 5th, 4 6th, 1 7th and 0 8th. two lines read the finished list, 6, 7, 5, 2, 3, 4, 1, 0, and that list reversed, 0, 1, 4, 3, 2, 5, 7, 6. every edge goes from a later finish to an earlier one, so in the reversed list every edge points forward. a line names the tasks, and a legend says what each ring and edge means.

complexity

dfsbfs
timeO(n + m)O(n + m)
extra spaceO(n): seen flags, and a stack up to n deepO(n): seen flags, and a queue of two levels
findsa path, and what can be reachedthe shortest path, by edges
the orderdives, a path at a timefans out, a level at a time

every reached vertex is pushed once, because it’s marked seen as it’s pushed, and popped once. between the two its index walks its list one entry per step, so every entry of every reached list is looked at once: 2m entries when the edges have no direction, since each is on two lists, m when they do. that’s n + 2m steps on this page’s count, 20 on the page’s graph: 6 visits and 14 looks. O(n + m), and the shape of the graph doesn’t change it.

02468108645124096every pair joined
a path
3.00 steps per vertex
a grid
4.94 steps per vertex
a random graph
5.00 steps per vertex
every pair joined
4,096 steps per vertex

a line chart of steps per vertex against how many vertices there are, from 8 to 4,096 on a doubling scale, with a slider that picks a size and reads off every line. per vertex, a line that stays flat is linear time. a path, solid cyan, sits just under 3: 2.75 at 8 and 3.00 at 4,096. a grid, dotted, climbs from 3.5 at 8 toward 5: 4.88 at 1,024 and 4.94 at 4,096. a random graph with about 2 edges per vertex, dashed cyan, goes from 3.75 at 8 to 5.00 at 4,096. every pair joined, amber, is at 8 for 8 vertices and off the top of the chart from 16 on: it costs n steps per vertex.

at 1,024 vertices a path takes 3,070 steps, a 32 by 32 grid 4,992, and a random graph with 2,041 edges 5,106: about 3, 5 and 5 per vertex. the complete graph on 1,024 vertices has 523,776 edges and takes 1,048,576 steps, n², and leaves the chart between 8 and 16 vertices. O(n + m) is linear only while m is. what the shape does change is the stack: on the path all 1,024 vertices are on it at once, on the grid too, and 602 of them on the random graph. a balanced binary tree costs the same steps as the path, 3,070, and is the one shape here that keeps the stack short: 11 deep. that depth is the recursive version’s call stack.

implementations

each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded graphs against a recursive dfs, 2000 seeded dags, and a path of 100,000 vertices in one pass, which the recursive version can’t do in python: its default recursion limit is 1,000 frames1. every tab visits in the same order, neighbors in list order, and gives the same topological order, the finish order reversed, so the tests pin the orders themselves. a cycle has no order: go returns false as a second value, rust None, typescript null, c sets its sorted out-param to false, swift nil, and python None. a start vertex out of range: go and rust stop where it’s first used as an index, typescript throws a RangeError, c returns false and writes nothing, swift stops on a precondition, and python raises an IndexError. typescript and python name the vertex, no vertex 6, and swift’s precondition carries the same words.

go/algos/dfs/dfs.go
// Package dfs is a reference depth-first search: go as deep as you can down one path, then back up and try
// the next. the vertices are 0 to n - 1, and adj[u] lists u's neighbors in the order to try them. both
// functions keep their own stack of pairs, a vertex and the index of its next neighbor, so the order
// matches a recursive dfs exactly and a deep graph can't overflow the call stack.
package dfs

import "slices"

// pair is one entry on the stack: a vertex, and the index of the next neighbor to look at.
type pair struct{ vertex, next int }

// Search returns the vertices src reaches, in the order a recursive dfs first visits them, neighbors in
// list order. A vertex is marked seen when it's pushed, so it's visited once. The pair on top says where
// we are and which neighbor to look at next: a new neighbor is visited and pushed, a seen one is skipped,
// and a vertex with none left is popped. A src outside 0 to n - 1 is a bug, and indexing with it panics.
func Search(adj [][]int, src int) []int {
	seen := make([]bool, len(adj))
	var order []int
	var stack []pair
	visit := func(v int) {
		seen[v] = true
		order = append(order, v)
		stack = append(stack, pair{v, 0})
	}
	visit(src)
	for len(stack) > 0 {
		top := len(stack) - 1
		u, i := stack[top].vertex, stack[top].next
		if i == len(adj[u]) {
			stack = stack[:top] // every neighbor of u is seen: u is done, back up
			continue
		}
		stack[top].next = i + 1 // move on, whatever v turns out to be
		if v := adj[u][i]; !seen[v] {
			visit(v) // new: go deeper
		}
	}
	return order
}

// The three states of a vertex in TopoSort.
const (
	unseen = iota // new: no dfs has reached it yet
	open          // its pair is on the stack: the dfs is still inside it
	done          // its pair has popped, and every vertex it leads to is done too
)

// TopoSort returns a topological order of a directed graph, adj[u] holding the edges u -> v: every edge
// points forward in it. ok is false if there's a cycle, a self-loop included. Every vertex, in index
// order, starts a dfs if it's still new. A vertex is open while its pair is on the stack and done once it
// pops, and the finish order reversed is the answer. An edge to an open vertex leads back to a vertex
// we're still inside: a cycle.
func TopoSort(adj [][]int) (order []int, ok bool) {
	state := make([]int, len(adj)) // every vertex starts unseen, the zero value
	finished := make([]int, 0, len(adj))
	for s := range adj {
		if state[s] != unseen {
			continue
		}
		state[s] = open
		stack := []pair{{s, 0}}
		for len(stack) > 0 {
			top := len(stack) - 1
			u, i := stack[top].vertex, stack[top].next
			if i == len(adj[u]) {
				state[u] = done // every edge out of u leads to a done vertex
				finished = append(finished, u)
				stack = stack[:top]
				continue
			}
			stack[top].next = i + 1
			v := adj[u][i]
			if state[v] == open {
				return nil, false // a back edge: a cycle
			}
			if state[v] == unseen {
				state[v] = open
				stack = append(stack, pair{v, 0})
			}
		}
	}
	slices.Reverse(finished)
	return finished, true
}
rust/algos/src/dfs.rs
//! dfs: go as deep as you can down one path, then back up and try the next. the vertices are 0 to n - 1, and adj[u] lists u's neighbors in the order to try them. both functions keep their own stack of pairs, a vertex and the index of its next neighbor, so the order matches a recursive dfs exactly and a deep graph can't overflow the call stack.

/// The vertices `src` reaches, in the order a recursive dfs first visits them, neighbors in list
/// order. A vertex is marked seen when it's pushed, so it's visited once. The pair on top says
/// where we are and which neighbor to look at next: a new neighbor is visited and pushed, a seen
/// one is skipped, and a vertex with none left is popped. A `src` past n - 1 panics, as any index
/// out of range does: there's no check of its own.
pub fn dfs(adj: &[Vec<usize>], src: usize) -> Vec<usize> {
    let mut seen = vec![false; adj.len()];
    // visit src: mark it, list it, push its pair
    seen[src] = true;
    let mut order = vec![src];
    let mut stack = vec![(src, 0)];
    while let Some(top) = stack.last_mut() {
        let (u, i) = *top;
        if i == adj[u].len() {
            stack.pop(); // every neighbor of u is seen: u is done, back up
            continue;
        }
        top.1 = i + 1; // move on, whatever v turns out to be
        let v = adj[u][i];
        if !seen[v] {
            // new: go deeper
            seen[v] = true;
            order.push(v);
            stack.push((v, 0));
        }
    }
    order
}

/// Where a vertex is in a topological sort.
#[derive(Clone, Copy, PartialEq)]
enum State {
    /// Not reached yet.
    New,
    /// Its pair is on the stack: the search is still inside it.
    Open,
    /// Popped: every edge out of it leads to a done vertex.
    Done,
}

/// A topological order of a directed graph, `adj[u]` holding the edges u -> v: every edge points
/// forward in it. `None` if there's a cycle, a self-loop included. Every vertex, in index order,
/// starts a dfs if it's still new. A vertex is open while its pair is on the stack and done once
/// it pops, and the finish order reversed is the answer. An edge to an open vertex leads back to a
/// vertex we're still inside: a cycle.
pub fn topo_sort(adj: &[Vec<usize>]) -> Option<Vec<usize>> {
    let n = adj.len();
    let mut state = vec![State::New; n];
    let mut finished = Vec::with_capacity(n);
    for s in 0..n {
        if state[s] != State::New {
            continue;
        }
        state[s] = State::Open;
        let mut stack = vec![(s, 0)];
        while let Some(top) = stack.last_mut() {
            let (u, i) = *top;
            if i == adj[u].len() {
                state[u] = State::Done; // every edge out of u leads to a done vertex
                finished.push(u);
                stack.pop();
                continue;
            }
            top.1 = i + 1;
            let v = adj[u][i];
            match state[v] {
                State::Open => return None, // a back edge: a cycle
                State::New => {
                    state[v] = State::Open;
                    stack.push((v, 0));
                }
                State::Done => {}
            }
        }
    }
    finished.reverse();
    Some(finished)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// xorshift32 seeded with `seed`, like the other tests here: each call gives the next number.
    fn xorshift32(seed: u32) -> impl FnMut() -> usize {
        let mut state = seed;
        move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        }
    }

    /// Lists for edges with no direction: each edge goes on both ends' lists, in the order given.
    fn undirected(n: usize, edges: &[(usize, usize)]) -> Vec<Vec<usize>> {
        let mut adj = vec![Vec::new(); n];
        for &(u, v) in edges {
            adj[u].push(v);
            adj[v].push(u);
        }
        adj
    }

    /// The plain recursive dfs: what the explicit stack has to match, visit for visit.
    fn recursive(adj: &[Vec<usize>], src: usize) -> Vec<usize> {
        fn go(adj: &[Vec<usize>], u: usize, seen: &mut [bool], order: &mut Vec<usize>) {
            seen[u] = true;
            order.push(u);
            for &v in &adj[u] {
                if !seen[v] {
                    go(adj, v, seen, order);
                }
            }
        }
        let mut order = Vec::new();
        go(adj, src, &mut vec![false; adj.len()], &mut order);
        order
    }

    // the graph page's graph: 6 vertices and 7 edges, lists built in edge order
    const EDGES: [(usize, usize); 7] = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 4), (3, 5), (4, 5)];

    /// The page's dag: 8 jobs in building a house. An edge u -> v says u has to be done before v.
    /// 0 foundation, 1 framing, 2 roof, 3 plumbing, 4 wiring, 5 drywall, 6 paint, 7 floors.
    fn tasks() -> Vec<Vec<usize>> {
        vec![
            vec![1],
            vec![2, 3, 4],
            vec![5],
            vec![5],
            vec![5],
            vec![6, 7],
            vec![],
            vec![],
        ]
    }

    #[test]
    fn the_pages_graph_from_0_0_1_2_4_5_3_from_3_3_1_0_2_4_5() {
        let page = undirected(6, &EDGES);
        assert_eq!(
            page,
            [
                vec![1, 2],
                vec![0, 2, 3],
                vec![0, 1, 4],
                vec![1, 5],
                vec![2, 5],
                vec![3, 4]
            ]
        );
        assert_eq!(dfs(&page, 0), [0, 1, 2, 4, 5, 3]);
        assert_eq!(dfs(&page, 3), [3, 1, 0, 2, 4, 5]);
    }

    #[test]
    fn one_vertex_just_itself_with_or_without_a_loop() {
        assert_eq!((dfs(&[vec![]], 0), dfs(&[vec![0]], 0)), (vec![0], vec![0]));
    }

    #[test]
    fn only_what_src_reaches_a_second_component_is_left_out_and_so_is_an_edge_into_src() {
        let two = undirected(5, &[(0, 1), (1, 2), (3, 4)]);
        assert_eq!((dfs(&two, 0), dfs(&two, 3)), (vec![0, 1, 2], vec![3, 4]));
        // the lists are followed as given: 2 -> 0 doesn't make 2 reachable from 0
        assert_eq!(dfs(&[vec![1], vec![], vec![0]], 0), [0, 1]);
    }

    #[test]
    fn matches_a_recursive_dfs_on_2000_seeded_graphs_self_loops_and_repeats_included() {
        let mut next = xorshift32(42);
        for _ in 0..2000 {
            let n = 1 + next() % 30;
            // 0 to 3 entries per list, any vertex at all
            let adj: Vec<Vec<usize>> = (0..n)
                .map(|_| (0..next() % 4).map(|_| next() % n).collect())
                .collect();
            let src = next() % n;
            assert_eq!(dfs(&adj, src), recursive(&adj, src));
        }
    }

    #[test]
    fn the_pages_dag_of_tasks_0_1_4_3_2_5_7_6_the_finish_order_reversed() {
        assert_eq!(topo_sort(&tasks()), Some(vec![0, 1, 4, 3, 2, 5, 7, 6]));
        // no edges: every vertex finishes as soon as it starts, so the order is the reverse of the
        // numbering
        assert_eq!(
            (topo_sort(&[]), topo_sort(&[vec![], vec![], vec![]])),
            (Some(vec![]), Some(vec![2, 1, 0]))
        );
    }

    #[test]
    fn every_vertex_once_and_every_edge_points_forward_on_2000_seeded_dags() {
        let mut next = xorshift32(7);
        for _ in 0..2000 {
            let n = 1 + next() % 30;
            // a hidden order: 0 to n - 1 shuffled. every edge goes from an earlier label to a later
            // one
            let mut label: Vec<usize> = (0..n).collect();
            for i in (1..n).rev() {
                label.swap(i, next() % (i + 1));
            }
            let mut adj = vec![Vec::new(); n];
            for _ in 0..next() % (2 * n + 1) {
                let i = next() % n;
                let j = next() % n;
                if i != j {
                    adj[label[i.min(j)]].push(label[i.max(j)]);
                }
            }
            let order = topo_sort(&adj).expect("a dag has an order");
            let mut sorted = order.clone();
            sorted.sort();
            assert_eq!(sorted, (0..n).collect::<Vec<_>>());
            let mut at = vec![0; n];
            for (i, &v) in order.iter().enumerate() {
                at[v] = i;
            }
            assert!((0..n).all(|u| adj[u].iter().all(|&v| at[u] < at[v])));
        }
    }

    #[test]
    fn a_cycle_gives_none_and_so_does_a_self_loop() {
        assert_eq!(
            (
                topo_sort(&[vec![1], vec![2], vec![0]]),
                topo_sort(&[vec![1], vec![0]]),
                topo_sort(&[vec![0]])
            ),
            (None, None, None)
        );
        // the dag with one edge back: the floors before the framing
        let mut back = tasks();
        back[7].push(1);
        assert_eq!(topo_sort(&back), None);
        // a cycle off to the side, after a vertex that's fine
        assert_eq!(topo_sort(&[vec![1], vec![2], vec![3], vec![2]]), None);
    }

    #[test]
    fn a_path_of_100_000_vertices_every_vertex_in_order_with_no_recursion() {
        let n = 100_000;
        let adj: Vec<Vec<usize>> = (0..n)
            .map(|i| if i + 1 < n { vec![i + 1] } else { vec![] })
            .collect();
        let order = dfs(&adj, 0);
        assert_eq!((order.len(), order[0], order[n - 1]), (n, 0, n - 1));
        assert!(order.iter().enumerate().all(|(i, &v)| v == i));
        assert_eq!(topo_sort(&adj), Some(order));
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn a_bad_src_panics() {
        // a usize can't be -1 or 1.5, so past the end is the only bad src there is
        dfs(&undirected(6, &EDGES), 6);
    }
}
site/src/visuals/dfs/dfs.ts
/**
 * Depth-first search: go as deep as you can down one path, then back up and try the next. The vertices are 0 to
 * n - 1, and adj[u] lists u's neighbors in the order to try them. Both functions keep their own stack of pairs, a
 * vertex and the index of its next neighbor, so the order matches a recursive dfs exactly and a deep graph can't
 * overflow the call stack.
 */

/**
 * The vertices src reaches, in the order a recursive dfs first visits them, neighbors in list order. A vertex is
 * marked seen when it's pushed, so it's visited once. The pair on top says where we are and which neighbor to
 * look at next: a new neighbor is visited and pushed, a seen one is skipped, and a vertex with none left is
 * popped. Throws a RangeError for a src outside 0 to n - 1.
 */
export function dfs(adj: readonly (readonly number[])[], src: number): number[] {
  if (!Number.isInteger(src) || src < 0 || src >= adj.length) throw new RangeError(`no vertex ${src}`);
  const seen: boolean[] = Array(adj.length).fill(false);
  const order: number[] = [];
  const stack: [number, number][] = [];
  const visit = (v: number) => {
    seen[v] = true;
    order.push(v);
    stack.push([v, 0]);
  };
  visit(src);
  while (stack.length > 0) {
    const top = stack[stack.length - 1];
    const [u, i] = top;
    if (i === adj[u].length) {
      stack.pop(); // every neighbor of u is seen: u is done, back up
      continue;
    }
    top[1] = i + 1; // move on, whatever v turns out to be
    const v = adj[u][i];
    if (!seen[v]) visit(v); // new: go deeper
  }
  return order;
}

/**
 * A topological order of a directed graph, adj[u] holding the edges u -> v: every edge points forward in it. It's
 * null if there's a cycle, a self-loop included. Every vertex, in index order, starts a dfs if it's still new. A
 * vertex is open while its pair is on the stack and done once it pops, and the finish order reversed is the
 * answer. An edge to an open vertex leads back to a vertex we're still inside: a cycle.
 */
export function topoSort(adj: readonly (readonly number[])[]): number[] | null {
  const NEW = 0;
  const OPEN = 1;
  const DONE = 2;
  const state: number[] = Array(adj.length).fill(NEW);
  const finished: number[] = [];
  for (let s = 0; s < adj.length; s++) {
    if (state[s] !== NEW) continue;
    state[s] = OPEN;
    const stack: [number, number][] = [[s, 0]];
    while (stack.length > 0) {
      const top = stack[stack.length - 1];
      const [u, i] = top;
      if (i === adj[u].length) {
        state[u] = DONE; // every edge out of u leads to a done vertex
        finished.push(u);
        stack.pop();
        continue;
      }
      top[1] = i + 1;
      const v = adj[u][i];
      if (state[v] === OPEN) return null; // a back edge: a cycle
      if (state[v] === NEW) {
        state[v] = OPEN;
        stack.push([v, 0]);
      }
    }
  }
  return finished.reverse();
}
c/algos/dfs.c
/* dfs: go as deep as you can down one path, then back up and try the next. both functions keep their own stack of pairs, a vertex and the index of its next neighbor, so the order matches a recursive dfs exactly and a deep graph can't overflow the call stack: a path of 100,000 vertices is 100,000 pairs on the heap, not 100,000 calls deep. */
#include "dfs.h"

#include <stdlib.h>

/* one frame of the recursion, kept by hand: a vertex, and the index of its next neighbor to look at */
typedef struct {
    size_t vertex, next;
} Pair;

/* a vertex is marked seen when it's pushed, so it's visited once. the pair on top says where we are
   and which neighbor to look at next: a new neighbor is visited and pushed, a seen one is skipped,
   and a vertex with none left is popped. the stack holds at most n pairs, one per seen vertex. once
   src is below n, n is at least 1, so neither allocation is one of 0 bytes */
bool dfs_order(const size_t *const *adj, const size_t *len, size_t n, size_t src, size_t *out, size_t *count) {
    *count = 0;
    if (src >= n) return false; /* no such vertex */
    bool *seen = calloc(n, sizeof *seen); /* calloc: nothing seen yet */
    Pair *stack = malloc(n * sizeof *stack);
    if (!seen || !stack) {
        free(seen);
        free(stack);
        return false;
    }
    size_t k = 0, top = 0; /* how many are in out, and how many pairs are on the stack */
    seen[src] = true;
    out[k++] = src;
    stack[top++] = (Pair){src, 0};
    while (top > 0) {
        Pair *p = &stack[top - 1];
        size_t u = p->vertex;
        if (p->next == len[u]) {
            top--; /* every neighbor of u is seen: u is done, back up */
            continue;
        }
        size_t v = adj[u][p->next++]; /* move on, whatever v turns out to be */
        if (seen[v]) continue;
        seen[v] = true; /* new: go deeper */
        out[k++] = v;
        stack[top++] = (Pair){v, 0};
    }
    free(seen);
    free(stack);
    *count = k;
    return true;
}

/* new: not seen yet. open: its pair is on the stack. done: popped, with every edge out of it leading
   to a done vertex */
typedef enum { NEW, OPEN, DONE } State;

/* every vertex, in index order, starts a dfs if it's still new. a vertex is open while its pair is
   on the stack and done once it pops, and the finish order reversed is the answer: each finished
   vertex goes into the next free slot from the back of out, so there's nothing to reverse. an edge
   to an open vertex leads back to a vertex we're still inside: a cycle. the stack holds at most n
   pairs, one per open vertex. n = 0 stops before the allocations: there's nothing to order, and
   calloc(0, ...) can return NULL, which would look like a failure */
bool dfs_topo_sort(const size_t *const *adj, const size_t *len, size_t n, size_t *out, bool *sorted) {
    *sorted = true;
    if (n == 0) return true;
    State *state = calloc(n, sizeof *state); /* calloc: every vertex starts NEW, which is 0 */
    Pair *stack = malloc(n * sizeof *stack);
    if (!state || !stack) {
        free(state);
        free(stack);
        *sorted = false;
        return false;
    }
    size_t left = n; /* the slots of out not written yet: out[0 .. left - 1] */
    bool cycle = false;
    for (size_t s = 0; s < n && !cycle; s++) {
        if (state[s] != NEW) continue;
        state[s] = OPEN;
        size_t top = 0;
        stack[top++] = (Pair){s, 0};
        while (top > 0 && !cycle) {
            Pair *p = &stack[top - 1];
            size_t u = p->vertex;
            if (p->next == len[u]) {
                state[u] = DONE;
                out[--left] = u; /* finished: it goes after everything finished later */
                top--;
                continue;
            }
            size_t v = adj[u][p->next++];
            if (state[v] == OPEN) cycle = true; /* a back edge */
            else if (state[v] == NEW) {
                state[v] = OPEN;
                stack[top++] = (Pair){v, 0};
            }
        }
    }
    free(state);
    free(stack);
    *sorted = !cycle;
    return true;
}
swift/algos/DFS.swift
/// dfs: go as deep as you can down one path, then back up and try the next. the vertices are 0 to n - 1, and adj[u] lists u's neighbors in the order to try them. both functions keep their own stack of pairs, a vertex and the index of its next neighbor, so the order matches a recursive dfs exactly and a deep graph can't overflow the call stack.

/// the vertices src reaches, in the order a recursive dfs first visits them, neighbors in list order. a vertex is
/// marked seen when it's pushed, so it's visited once. the pair on top says where we are and which neighbor to
/// look at next: a new neighbor is visited and pushed, a seen one is skipped, and a vertex with none left is
/// popped. a src outside 0 to n - 1 traps
public func dfs(_ adj: [[Int]], _ src: Int) -> [Int] {
    precondition(0 <= src && src < adj.count, "no vertex \(src)")
    var seen = [Bool](repeating: false, count: adj.count)
    var order: [Int] = []
    var stack: [(vertex: Int, next: Int)] = []
    func visit(_ v: Int) {
        seen[v] = true
        order.append(v)
        stack.append((v, 0))
    }
    visit(src)
    while let top = stack.last {
        let (u, i) = top
        if i == adj[u].count {
            stack.removeLast() // every neighbor of u is seen: u is done, back up
            continue
        }
        stack[stack.count - 1].next = i + 1 // move on, whatever v turns out to be
        let v = adj[u][i]
        if !seen[v] { visit(v) } // new: go deeper
    }
    return order
}

/// a topological order of a directed graph, adj[u] holding the edges u -> v: every edge points forward in it. nil
/// if there's a cycle, a self-loop included. every vertex, in index order, starts a dfs if it's still new. a vertex
/// is open while its pair is on the stack and done once it pops, and the finish order reversed is the answer. an
/// edge to an open vertex leads back to a vertex we're still inside: a cycle
public func topoSort(_ adj: [[Int]]) -> [Int]? {
    enum State { case new, open, done }
    var state = [State](repeating: .new, count: adj.count)
    var finished: [Int] = []
    for s in adj.indices where state[s] == .new {
        state[s] = .open
        var stack = [(vertex: s, next: 0)]
        while let top = stack.last {
            let (u, i) = top
            if i == adj[u].count {
                state[u] = .done // every edge out of u leads to a done vertex
                finished.append(u)
                stack.removeLast()
                continue
            }
            stack[stack.count - 1].next = i + 1
            let v = adj[u][i]
            if state[v] == .open { return nil } // a back edge: a cycle
            if state[v] == .new {
                state[v] = .open
                stack.append((v, 0))
            }
        }
    }
    return finished.reversed()
}
python/algos/dfs.py
"""dfs: go as deep as you can down one path, then back up and try the next. the vertices are 0 to n - 1, and adj[u] lists u's neighbors in the order to try them. both functions keep their own stack of pairs, a vertex and the index of its next neighbor, so the order matches a recursive dfs exactly and a deep graph can't overflow the call stack."""

from __future__ import annotations

# where topo_sort stands with each vertex: not reached yet, its pair on the stack, or popped
NEW, OPEN, DONE = 0, 1, 2


def dfs(adj: list[list[int]], src: int) -> list[int]:
    """Return the vertices src reaches, in the order a recursive dfs first visits them.

    Neighbors are tried in list order. A vertex is marked seen when it's pushed, so it's visited once. The
    pair on top says where we are and which neighbor to look at next: a new neighbor is visited and pushed, a
    seen one is skipped, and a vertex with none left is popped. A src outside 0 to n - 1 raises IndexError.
    """
    if not 0 <= src < len(adj):
        raise IndexError(f"no vertex {src}")  # a negative src would count from the end of the list
    seen = [False] * len(adj)
    order: list[int] = []
    stack: list[tuple[int, int]] = []  # (vertex, the index of its next neighbor)

    def visit(v: int) -> None:
        seen[v] = True
        order.append(v)
        stack.append((v, 0))

    visit(src)
    while stack:
        u, i = stack[-1]
        if i == len(adj[u]):
            stack.pop()  # every neighbor of u is seen: u is done, back up
            continue
        stack[-1] = (u, i + 1)  # move on, whatever v turns out to be
        v = adj[u][i]
        if not seen[v]:
            visit(v)  # new: go deeper
    return order


def topo_sort(adj: list[list[int]]) -> list[int] | None:
    """Return a topological order of a directed graph, adj[u] holding the edges u -> v.

    Every edge points forward in it. None if there's a cycle, a self-loop included. Every vertex, in index
    order, starts a dfs if it's still new. A vertex is open while its pair is on the stack and done once it
    pops, and the finish order reversed is the answer. An edge to an open vertex leads back to a vertex we're
    still inside: a cycle.
    """
    state = [NEW] * len(adj)
    finished: list[int] = []
    for s in range(len(adj)):
        if state[s] != NEW:
            continue
        state[s] = OPEN
        stack = [(s, 0)]
        while stack:
            u, i = stack[-1]
            if i == len(adj[u]):
                state[u] = DONE  # every edge out of u leads to a done vertex
                finished.append(u)
                stack.pop()
                continue
            stack[-1] = (u, i + 1)
            v = adj[u][i]
            if state[v] == OPEN:
                return None  # a back edge: a cycle
            if state[v] == NEW:
                state[v] = OPEN
                stack.append((v, 0))
    finished.reverse()
    return finished

pitfalls

variants

practice

how real libraries do it

sources

  1. pycore_ceval.h (opens in a new tab) in cpython 3.15.0 sets Py_DEFAULT_RECURSION_LIMIT to 1000 unless it’s defined already, and pycore_runtime_init.h (opens in a new tab) starts each interpreter with that limit. the sys docs (opens in a new tab) say the limit stops infinite recursion from overflowing the c stack and crashing python, that the highest limit the platform allows varies, and that setting it too high can lead to a crash. ↩ ↩2

  2. robert tarjan, depth-first search and linear graph algorithms (opens in a new tab), siam journal on computing 1(2), 146–160, june 1972. its abstract, as siam registered it with crossref, says the paper shows depth-first search at work on two problems: an algorithm for the strongly connected components of a directed graph, and one for the biconnected components of an undirected graph, each in time and space linear in the vertices and edges. ↩

  3. graphlib.py (opens in a new tab) in cpython 3.15.0: each node keeps npredecessors, the number of predecessors not yet done, and a list of successors. prepare (opens in a new tab) takes the nodes with no predecessors as ready and then looks for a cycle, done (opens in a new tab) lowers each successor’s count and makes it ready when the count reaches 0, and static_order (opens in a new tab) loops over prepare, get_ready and done. _find_cycle (opens in a new tab) is the dfs: a stack of nodes, a stack of iterators over their successors, and a map from a node to its place on the stack, so a node met again while on the stack hands back the cycle as the slice of the stack from it. ↩ ↩2

  4. depth_first_search.py (opens in a new tab) in networkx 3.7: dfs_edges keeps a set of visited nodes and a stack of (parent, children) pairs, children being an iterator. it looks at the top’s next child, and when the child is new yields the edge, marks it and pushes it, within the depth limit; when the iterator runs out it pops. topological_sort (opens in a new tab) yields from topological_generations (opens in a new tab), which keeps a map of in-degrees, takes the nodes with in-degree 0 as a generation, lowers each child’s count as its parents go out, and raises NetworkXUnfeasible when counts are left over, since that means a cycle. ↩ ↩2

  5. rev-list-options.adoc (opens in a new tab) in git 2.56.0: --topo-order shows no parents before all of its children are shown and avoids showing commits from several lines of history intermixed. commit.c (opens in a new tab): sort_in_topological_order gives every commit in the list an in-degree of 1, adds one to a parent’s for each of its children in the list, queues the tips, the commits still at 1, and as each commit comes off the queue lowers its parents’ counts, queueing a parent only when all of its children have been emitted, which its comment says guarantees topological order. without generation numbers, revision.c (opens in a new tab) has to walk every commit first and then sort them that way. with them, from a commit-graph, it walks incrementally (opens in a new tab) instead: indegree_walk_step (opens in a new tab) runs the same count a step at a time, from a queue ordered by generation number, then commit date (opens in a new tab). ↩ ↩2