BFS, DFS and topological sort: how they work

How to walk a graph or a grid level by level (BFS) or path by path (DFS), and how to put tasks in an order that respects every rule (topological sort).

Updated About 6 minutes to read

On this page

The video

Maximum Depth of Binary Tree

LeetCode 104Open the video page

Chapters

  1. Play from 0:00How tall is the tree?
  2. Play from 0:13What depth means
  3. Play from 0:26The example tree
  4. Play from 0:45Ask both children
  5. Play from 0:59Where the recursion stops
  6. Play from 1:11The code in JavaScript
  7. Play from 1:26Running it on the tree
  8. Play from 1:47How fast it is
  9. Play from 2:03Counting levels without recursion
  10. Play from 2:16Recap

Transcript

Show the whole transcriptHide the transcript
  1. Play from 0:00

    How tall is a binary tree?

  2. Play from 0:05

    That is LeetCode problem one hundred four, and we will solve it in JavaScript.

  3. Play from 0:13

    The depth of a tree is the number of nodes on the longest path.

  4. Play from 0:17

    That path starts at the root, at the top, and goes down to the farthest leaf.

  5. Play from 0:23

    A leaf is a node with no children.

  6. Play from 0:26

    Here is our example tree.

  7. Play from 0:28

    The root holds three.

  8. Play from 0:30

    Its children are nine and twenty.

  9. Play from 0:33

    Twenty has two children, fifteen and seven.

  10. Play from 0:37

    The longest path is three, twenty, fifteen.

  11. Play from 0:41

    That path has three nodes, so the answer is three.

  12. Play from 0:45

    Here is the key idea.

  13. Play from 0:47

    A node does not need to see the whole tree.

  14. Play from 0:50

    It asks its left child and its right child how deep they go.

  15. Play from 0:54

    Then it takes the bigger answer and adds one for itself.

  16. Play from 0:59

    Every recursion needs a place to stop.

  17. Play from 1:02

    If a node is empty, there is nothing there, so its depth is zero.

  18. Play from 1:07

    In JavaScript, an empty child is null.

  19. Play from 1:11

    Here is the whole function.

  20. Play from 1:13

    First, if the root is null, return zero.

  21. Play from 1:17

    Next, find the depth of the left subtree.

  22. Play from 1:20

    Then find the depth of the right subtree.

  23. Play from 1:23

    Finally, return one plus the larger of the two.

  24. Play from 1:27

    Let us run it on our tree.

  25. Play from 1:29

    Nine, fifteen and seven are leaves.

  26. Play from 1:32

    Their children are null, so each leaf returns one.

  27. Play from 1:36

    Twenty gets one from each side, so it returns two.

  28. Play from 1:39

    The root gets one from nine and two from twenty.

  29. Play from 1:43

    It returns one plus two, which is three.

  30. Play from 1:47

    How fast is this?

  31. Play from 1:49

    We visit every node once, so the time grows in a straight line with the number of nodes.

  32. Play from 1:54

    The extra memory is the call stack, one frame for each level we go down.

  33. Play from 1:58

    For a tree shaped like a long chain, that is one frame per node.

  34. Play from 2:03

    You can also count levels without recursion.

  35. Play from 2:07

    Keep a queue of the nodes on one level.

  36. Play from 2:10

    Process the whole level, add the next level, and count one each time.

  37. Play from 2:16

    To sum up, the depth of a tree is one plus the deeper of its two subtrees, and an empty tree has depth zero.

A graph is a set of things connected by links. The things are called nodes, and the links are called edges. Cities and roads, people and friendships, or courses and their prerequisites are all graphs. A grid is a graph too: each cell is a node, linked to the cells above, below, left and right. Breadth-first search (BFS) and depth-first search (DFS) are the two standard ways to visit every node you can reach. Topological sort uses the same ideas to put tasks in a valid order.

The idea in one minute

Both searches start at one node, visit it, then visit its neighbors, then their neighbors, and so on. They keep a record of what they've already seen, so no node is visited twice. The difference is the order:

  • BFS goes level by level. First every node one step away, then every node two steps away. It uses a queue: a line where the first one in is the first one out.
  • DFS goes as deep as it can, then backs up. It follows one path to its end before trying the next. It uses a stack, where the last one in is the first one out, or a function that calls itself.

Both visit the same nodes. BFS has one extra power: in a graph where every edge counts the same, it reaches each node by the fewest steps.

Topological sort orders tasks so that every task comes after the ones it depends on. It only works if no tasks depend on each other in a circle.

When to use it

  • Count or mark connected groups. Islands on a map, friend circles, regions of the same color. Either search works.
  • Fewest steps from one place to another, when every move costs the same. Use BFS.
  • Explore every path, or check if any path exists. DFS is often the shorter code.
  • Tasks with prerequisites. "Can all of these be done?" or "In what order?" Use topological sort.
  • The input is a grid, a list of pairs like [a, b], or a map from each node to its neighbors.

Worked example 1: Number of Islands

This is LeetCode 200, Number of Islands. In our words: a grid holds land (1) and water (0). Land cells that touch up, down, left or right belong to the same island. How many islands are there?

1 1 0 0 1
1 0 0 1 1
0 0 1 0 0
0 0 0 0 1

Scan the grid row by row. Each time you find land you haven't seen yet, that's a new island. Run a BFS from it to mark the whole island as seen.

found at (row, col) island cells it marks
(0,0) 1 (0,0) (1,0) (0,1)
(0,4) 2 (0,4) (1,4) (1,3)
(2,2) 3 (2,2)
(3,4) 4 (3,4)

The scan passes every other land cell, but they're already marked, so they don't start new islands. The answer is 4.

Notice (1,3) and (2,2). They touch only at a corner, so they're on different islands.

The code in JavaScript

BFS on a grid

The queue is an array with a head index, instead of shift(), which can be slow on long arrays. Cells are marked as seen when they're added to the queue.

function numIslands(grid) {
  const rows = grid.length;
  const cols = grid[0].length;
  const seen = grid.map((row) => new Array(row.length).fill(false));
  const moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]; // down, up, right, left
  let islands = 0;

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] !== "1" || seen[r][c]) continue;
      islands++; // new land: a new island
      const queue = [[r, c]];
      seen[r][c] = true;
      for (let head = 0; head < queue.length; head++) {
        const [y, x] = queue[head];
        for (const [dy, dx] of moves) {
          const ny = y + dy;
          const nx = x + dx;
          if (ny < 0 || ny >= rows || nx < 0 || nx >= cols) continue;
          if (grid[ny][nx] === "1" && !seen[ny][nx]) {
            seen[ny][nx] = true;
            queue.push([ny, nx]);
          }
        }
      }
    }
  }
  return islands;
}

numIslands(["11001", "10011", "00100", "00001"]); // 4

DFS on a grid

The same count with DFS is shorter, because the function calls itself for each neighbor. It's fine for small grids. On a very large island, the chain of calls gets too deep and JavaScript stops with "Maximum call stack size exceeded". BFS doesn't have that problem.

function numIslandsDfs(grid) {
  const seen = new Set();
  const visit = (r, c) => {
    if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) return;
    if (grid[r][c] !== "1" || seen.has(`${r},${c}`)) return;
    seen.add(`${r},${c}`);
    visit(r + 1, c);
    visit(r - 1, c);
    visit(r, c + 1);
    visit(r, c - 1);
  };
  let islands = 0;
  for (let r = 0; r < grid.length; r++) {
    for (let c = 0; c < grid[0].length; c++) {
      if (grid[r][c] === "1" && !seen.has(`${r},${c}`)) {
        islands++;
        visit(r, c);
      }
    }
  }
  return islands;
}

numIslandsDfs(["11001", "10011", "00100", "00001"]); // 4

Worked example 2: Course Schedule

This is LeetCode 207, Course Schedule. In our words: there are n courses, numbered from 0. Each rule [a, b] means you must finish course b before course a. Can you finish every course?

You can, unless some courses wait on each other in a circle. Kahn's method checks this by building an order:

  1. For each course, count how many courses must come before it. This count is its in-degree.
  2. Put every course with a count of 0 in a queue. They're ready now.
  3. Take a course from the queue and add it to the order. Each course that was waiting on it has its count lowered by 1. Any that reach 0 join the queue.
  4. Repeat until the queue is empty. If every course made it into the order, you can finish them all. If not, the courses left over are in a circle, or wait on one that is.

Take 4 courses and the rules [1, 0], [2, 0], [3, 1], [3, 2]. Course 0 comes first. Courses 1 and 2 need 0. Course 3 needs both 1 and 2.

take counts after (0, 1, 2, 3) queue after
start 0, 1, 1, 2 0
0 done, 0, 0, 2 1, 2
1 done, done, 0, 1 2
2 done, done, done, 0 3
3 done, done, done, done empty

All 4 courses are in the order 0, 1, 2, 3, so the answer is yes.

Now add the rule [0, 3]: course 0 needs course 3. Every course now waits on another one, so no count is ever 0. The queue starts empty, nothing gets taken, and the answer is no.

function courseOrder(n, rules) {
  const next = Array.from({ length: n }, () => []); // b -> courses that need b
  const waitingOn = new Array(n).fill(0); // the in-degree of each course
  for (const [a, b] of rules) {
    next[b].push(a);
    waitingOn[a]++;
  }
  const queue = [];
  for (let c = 0; c < n; c++) if (waitingOn[c] === 0) queue.push(c);
  for (let head = 0; head < queue.length; head++) {
    for (const a of next[queue[head]]) {
      waitingOn[a]--;
      if (waitingOn[a] === 0) queue.push(a);
    }
  }
  return queue.length === n ? queue : null; // null: some courses form a circle
}

const canFinish = (n, rules) => courseOrder(n, rules) !== null;

courseOrder(4, [[1, 0], [2, 0], [3, 1], [3, 2]]); // [0, 1, 2, 3]
canFinish(4, [[1, 0], [2, 0], [3, 1], [3, 2], [0, 3]]); // false

The queue doubles as the answer. Everything that passed through it, in that order, is a valid order of courses.

How fast is it?

Programmers describe speed with Big-O notation. It says how the work grows as the input grows. O(n) means the work grows in step with n.

For graphs, two sizes matter: V, the number of nodes, and E, the number of edges.

  • BFS and DFS: O(V + E) time. Each node is visited once, and each edge is looked at once or twice.
  • On a grid: O(rows × cols). Each cell has at most 4 neighbors, so the edges add only a fixed amount per cell.
  • Memory: O(V) for the seen marks, plus the queue, the stack or the chain of calls.
  • Course order: O(V + E). Each course enters the queue once, and each rule lowers one count once.

Common mistakes

  • Marking cells as seen too late. Mark a cell when you add it to the queue, not when you take it out. Otherwise the same cell can be added many times.
  • Using shift() for the queue. By the language rules, it moves every other item down one place. On a long queue that adds up. Keep a head index instead.
  • Deep recursion. A recursive DFS on a 1,000 by 1,000 grid of land can need up to a million calls waiting at once. Use BFS or a stack you manage yourself.
  • Getting the direction of a rule backwards. In Course Schedule, [a, b] means b comes first. Draw one rule as an arrow before you code.
  • Counting corner neighbors. If the problem says up, down, left and right, don't add the 4 diagonal moves.
  • Starting from only one node. A graph can have several separate parts. Loop over every node, as the island scan does.

Practice problems

  1. LeetCode 733, Flood Fill. One BFS or DFS from a single cell.
  2. LeetCode 695, Max Area of Island. Number of Islands, but count the cells of each one.
  3. LeetCode 994, Rotting Oranges. BFS from many starting cells at once, counting levels.
  4. LeetCode 547, Number of Provinces. Connected groups, with the graph given as a table.
  5. LeetCode 210, Course Schedule II. Return the order itself. courseOrder does most of it.
  6. LeetCode 133, Clone Graph. Walk the graph and copy each node once.

In short

BFS visits a graph level by level with a queue, and finds the fewest steps. DFS follows one path as deep as it can. Topological sort repeatedly takes the tasks with nothing left to wait for, and if some tasks never get free, they form a circle.

Want a video for a different problem?

Type a problem, a pattern or a system to design. You get a narrated video like the one above, usually ready in 5 to 9 minutes.

3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing

Make a video