Find a course

Module 5: Graphs and Algorithm DesignLesson 12 of 1314 min

Graphs, BFS and DFS

Represent graphs with adjacency lists and matrices, find shortest paths in unweighted graphs with breadth-first search, and explore with depth-first search.

Step 1 of 10Learn

Everything is connected

Road maps, social networks, web pages and their links, airline routes, computer networks, task dependencies in a project: all of them are about connections. The structure that models connections is the graph.

A graph has vertices (also called nodes) and edges connecting pairs of vertices. Important variations:

  • Undirected edges go both ways, like a friendship or a two-way street. Directed edges have a direction, like following someone on social media, a one-way street or a web link.
  • Weighted edges carry a number, such as distance, travel time or cost. Unweighted edges just indicate a connection.
  • A path is a sequence of vertices connected by edges. A cycle is a path that returns to its start.
  • The degree of a vertex is the number of edges touching it; in directed graphs, we count in-degree and out-degree separately.
  • A graph is connected if there's a path between every pair of vertices.

Trees are a special case: a connected, undirected graph with no cycles. A directed graph with no cycles is called a DAG (directed acyclic graph), and it's used for things like course prerequisites and build systems, where some tasks must come before others.

Graph size is described with two numbers: V, the number of vertices, and E, the number of edges. Graph algorithm costs are usually written in terms of both, like O(V + E).

Undirected graph (edges go both ways, like friendships) versus directed graph (one-way edges, like follows)ABCDABCDundirecteddirected

Step 2 of 10Practice · Sort into groups

Should each situation be modeled with directed or undirected edges?

Tap an item, then tap its group (or drag it there).

Step 3 of 10Learn

Representing a graph

There are two main ways to store a graph.

An adjacency matrix is a V × V grid where entry [i][j] is 1 (or the edge's weight) if there's an edge from i to j, and 0 otherwise.

  • Checking whether a specific edge exists is O(1).
  • It always uses O(V²) memory, even if there are few edges.
  • Listing a vertex's neighbors means scanning a whole row: O(V).

An adjacency list stores, for each vertex, a list of its neighbors.

  • It uses O(V + E) memory.
  • Listing a vertex's neighbors takes time proportional to its degree, which is what most algorithms need.
  • Checking a specific edge means scanning one list, unless you store neighbors in sets.

Most real graphs are sparse: each vertex connects to only a few others. A social network with a billion users might average a few hundred friends each. An adjacency matrix for it would need 10¹⁸ entries; an adjacency list needs space for the edges that actually exist. So adjacency lists are the usual default, and matrices are used for small or dense graphs.

In JavaScript, an adjacency list is often an object or Map from each vertex to an array of neighbors:

const graph = {
  A: ['B', 'C'],
  B: ['A', 'D'],
  C: ['A', 'D'],
  D: ['B', 'C', 'E'],
  E: ['D']
};

In an undirected graph, each edge appears twice, once in each endpoint's list.

The same four-vertex graph stored as an adjacency matrix and as an adjacency listadjacency matrixAABBCCDD0110100110010110adjacency listA: B, CB: A, DC: A, DD: B, CO(V²) memory, O(1) edge checkO(V + E) memory

Step 4 of 10Practice · Work it out

An undirected graph has 1,000 vertices and 3,000 edges, stored as an adjacency list. How many neighbor entries do the lists contain in total?

Step 5 of 10Learn

Breadth-first search

Breadth-first search (BFS) explores a graph in rings: first the start vertex, then all its neighbors, then all their unvisited neighbors, and so on. It uses a queue and a visited set:

  1. Mark the start as visited and enqueue it.
  2. While the queue isn't empty, dequeue a vertex v.
  3. For each neighbor of v that hasn't been visited, mark it visited and enqueue it.

Because vertices are processed in order of distance, BFS discovers each vertex along a path with the fewest edges. That makes it the algorithm for shortest paths in unweighted graphs: the fewest moves in a puzzle, the fewest hops between two computers, the degrees of separation between two people. To report distances, store each vertex's distance as one more than the vertex that discovered it.

Marking vertices as visited when they're enqueued, not when dequeued, prevents the same vertex from entering the queue many times. Without a visited set, BFS on a graph with cycles would loop forever.

Every vertex is enqueued at most once, and every edge is examined at most twice, so BFS runs in O(V + E) time with an adjacency list, and uses O(V) memory for the queue and visited set.

One important limit: BFS finds the path with the fewest edges, which isn't necessarily the shortest in distance when edges have different weights. For weighted graphs with non-negative weights, Dijkstra's algorithm generalizes BFS by replacing the queue with a priority queue ordered by distance so far.

Step 6 of 10Practice · Code challenge

Write bfsDistance(graph, start, goal) that returns the number of edges on the shortest path from start to goal in an unweighted graph given as an adjacency-list object (like { A: ['B'], B: ['A'] }). Return 0 if start equals goal and -1 if goal can't be reached.

Runs in a sandbox in your browser.
  • bfsDistance({ A: ['B', 'C'], B: ['A', 'D'], C: ['A', 'D'], D: ['B', 'C', 'E'], E: ['D'] }, 'A', 'E')
  • bfsDistance({ A: ['B'], B: ['A'] }, 'A', 'A')
  • bfsDistance({ A: ['B'], B: ['A'], C: [] }, 'A', 'C')
  • bfsDistance({ S: ['A', 'B'], A: ['C'], B: ['C'], C: ['G'], G: [] }, 'S', 'G')
  • bfsDistance({ A: ['B', 'E'], B: ['C'], C: ['D'], D: ['E'], E: [] }, 'A', 'E')

Step 7 of 10Learn

Depth-first search

Depth-first search (DFS) takes the opposite approach: go as far as possible along one path, and only backtrack when you hit a dead end. It uses a stack, either explicitly or through recursion:

function dfs(graph, v, visited = new Set()) {
  visited.add(v);
  for (const n of graph[v] || []) {
    if (!visited.has(n)) dfs(graph, n, visited);
  }
  return visited;
}

Like BFS, DFS visits each vertex once and examines each edge a constant number of times: O(V + E). It doesn't find shortest paths, but its deep-first order makes it ideal for other tasks:

  • Reachability and connected components: run DFS from each unvisited vertex; each run discovers one component. Counting islands on a grid map is a classic example.
  • Cycle detection: in a directed graph, reaching a vertex that's still on the current DFS path means there's a cycle.
  • Topological sort: in a DAG, listing vertices in reverse order of when DFS finishes them gives an order where every edge points forward, such as a valid order to take courses given prerequisites, or to build software modules.
  • Maze solving and backtracking searches, which naturally follow one path until it fails.

One practical warning: recursive DFS on a very deep graph can overflow the call stack. For large graphs, an explicit stack in a loop is safer.

Step 8 of 10Compare

BFS vs. DFS

AspectBreadth-first searchDepth-first search
Data structureQueueStack or recursion
Exploration orderLevel by level, nearest firstOne path as deep as possible, then backtrack
Shortest path (unweighted)Yes, fewest edgesNo
Typical usesFewest moves, degrees of separation, level-order traversalCycle detection, topological sort, components, mazes
Time with adjacency listO(V + E)O(V + E)
Memory riskWide graphs make the queue largeDeep graphs make the stack deep

Step 9 of 10Practice · Match the pairs

Match each problem to the most suitable algorithm.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Fewest moves to solve a sliding puzzle
  2. Fastest driving route on roads with travel times
  3. A valid order to take courses given their prerequisites
  4. Counting separate islands on a grid map

Step 10 of 10Practice · Choose one

Why must BFS and DFS keep track of visited vertices?