DSA Basics: Graphs

Learn graph terminology, adjacency lists, BFS, DFS, and when graph thinking is useful.

Back to Learn DSA

A graph is a set of nodes connected by edges.

Graphs are useful when relationships matter more than order. Social networks, maps, dependency graphs, and recommendation systems can all be modeled as graphs.

Terms

Adjacency list

An adjacency list stores each node with the nodes connected to it.

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

BFS explores neighbors level by level and uses a queue.

function bfs(graph, start) {
	const visited = new Set([start]);
	const queue = [start];

	while (queue.length > 0) {
		const node = queue.shift();
		console.log(node);

		for (const neighbor of graph[node]) {
			if (!visited.has(neighbor)) {
				visited.add(neighbor);
				queue.push(neighbor);
			}
		}
	}
}

DFS goes deep before backtracking. It can be written with recursion or a stack.

Practice problems

  1. Count connected components.
  2. Find if a path exists.
  3. Clone a graph.
  4. Find shortest path in an unweighted graph.
  5. Detect a cycle.

Interactive walkthrough

Graph Search Visualizer

Explore connected nodes while tracking visited nodes.
Step 1 start
Step 2 queue
Step 3 visited
Step 4 neighbor