Lesson 2 · Non-linear structures

Graph Data Structures and Traversal

A graph is a set of vertices joined by edges, with no root and no fixed shape. This lesson covers the kinds of graph, the two main ways to store one, and how a search walks it without going round in circles.

Graph Data Structures and Traversal concept diagramA visual explanation of the layout and operations shown in this lesson.ABCDEvertices + edges model arbitrary relationships
1

Vertices, Edges, and What They Model

A graph data structure is a set of vertices (nodes) and a set of edges, each edge joining two vertices. That is the whole definition. There is no root, no order, no limit on how many edges a vertex has, and no rule that every vertex can reach every other.

That freedom is why other structures are special cases. A linked list is a graph where each vertex has at most one outgoing edge. A tree is a connected graph with no cycles, which always has exactly n − 1 edges for n vertices.

Most of the difficulty in a graph problem is the modelling. Decide what a vertex is and what an edge is. For a road map, vertices are junctions and edges are roads. For a build system, vertices are targets and edges are dependencies. For a word ladder, vertices are words and edges join words that differ by one letter. Once that is written down, the question usually becomes a standard one: shortest path, reachability, cycle detection or ordering.

The degree of a vertex is the number of edges touching it. In a directed graph it splits into in-degree (edges arriving) and out-degree (edges leaving). Topological sort works by repeatedly removing vertices whose in-degree has dropped to zero.

  • A question about connections between things, rather than the things, is usually a graph problem
  • In an undirected graph, the degrees add up to 2E, because each edge has two ends
  • A simple undirected graph has at most V(V − 1)/2 edges; a directed one at most V(V − 1)
2

The Types of Graph

The types of graph that data structure courses list are really independent properties, not separate kinds. Every graph has a value for each, and they combine freely.

Directed or undirected. An undirected edge works both ways, like a friendship or two touching rooms. A directed edge works one way, like a one-way street, a web link or a dependency. Telling a directed and undirected graph apart matters: cycle detection, for one, uses a different method in each.

Weighted or unweighted. In a weighted graph each edge carries a number: distance, cost, time or capacity. Unweighted edges all count as 1. This choice decides the shortest-path method: BFS for unweighted, Dijkstra for non-negative weights, Bellman–Ford when some weights are negative.

Cyclic or acyclic. A cycle is a path that returns to its start. A directed graph with no cycle is a DAG, the shape of every dependency problem: build steps, course prerequisites, task scheduling. Only a DAG has a topological order.

Connected or not. An undirected graph is connected if every vertex can reach every other; otherwise it falls into separate components. For directed graphs, strongly connected means a path both ways between every pair.

A few more names: dense (close to V² edges) and sparse (close to V edges); complete (an edge between every pair); bipartite (vertices split into two groups, with edges only between the groups, which a search can test by two-colouring).

  • A tree is undirected, connected and acyclic all at once
  • A self-loop is an edge from a vertex to itself; a multigraph allows several edges between the same pair
  • Store an undirected edge as two directed entries, u → v and v → u
3

Adjacency List or Adjacency Matrix

Two ways of storing a graph dominate, and the wrong choice can multiply a search's cost by V.

An adjacency list keeps, for each vertex, a list of its neighbours. Space is O(V + E): only what exists is stored. Listing a vertex's neighbours takes time proportional to its degree, which is exactly what BFS and DFS do. The weak spot is asking whether one particular edge u → v exists, which means scanning u's list.

An adjacency matrix is a V × V grid where cell [u][v] holds 1 (or the weight) if the edge exists. Checking one edge is O(1). But the grid takes O(V²) space however few edges there are, and listing one vertex's neighbours means reading a whole row of V cells.

Real graphs are almost always sparse: a road junction meets a handful of roads, not thousands. So the list is the default, and the matrix is kept for dense graphs or for algorithms that look up specific pairs over and over, such as Floyd–Warshall.

A third form, the edge list, is just a list of (u, v, weight) entries. It cannot list a vertex's neighbours quickly, but it is the usual input format and exactly what Kruskal's algorithm wants, since it sorts all edges and never asks about one vertex.

The two main representations compared
Adjacency listAdjacency matrix
SpaceO(V + E)O(V²)
Is there an edge u → v?O(degree of u)O(1)
List u's neighboursO(degree of u)O(V)
BFS or DFS over the graphO(V + E)O(V²)
Best forSparse graphs, which most real ones areDense graphs, Floyd–Warshall
  • A million vertices with ten edges each: about 10⁷ list entries against 10¹² matrix cells
  • Putting each list in a hash set makes the edge check O(1) on average
  • Vertices named by strings need a map from name to list, or a renumbering to 0..V − 1
Key reference

Terms, operations, and practical uses

Graph terminology

  • VertexOne thing in the model: a junction, a person, a task, a web page.
  • EdgeA connection between two vertices, one-way if directed, with a number if weighted.
  • PathA sequence of vertices where each consecutive pair is joined by an edge.
  • ComponentA largest group of vertices that can all reach each other.

Representation

  • Adjacency listEach vertex's neighbours, O(V + E) space; the default for sparse graphs.
  • Adjacency matrixA V × V grid, O(V²) space, with an O(1) check for any single edge.
  • Edge listAll edges as (u, v, weight) entries; suits algorithms that sort or scan every edge.

Traversal choices

  • BFSA queue; visits vertices in rings of distance from the start.
  • DFSA stack or recursion; follows one branch to its end before trying the next.
  • Visited setMarks vertices when first found, so cycles cannot queue the same vertex again.
Implementation

Code in Python, C++ and Java

from collections import deque

def bfs(graph, start):
    queue = deque([start])
    seen = {start}
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in graph[node]:
            if neighbor not in seen:
                seen.add(neighbor)
                queue.append(neighbor)
    return order


graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['E'], 'D': [], 'E': []}
print(*bfs(graph, 'A'))
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

vector<char> bfs(const vector<vector<int>>& graph, int start) {
    queue<int> pending;
    vector<bool> seen(graph.size());
    vector<char> order;
    pending.push(start);
    seen[start] = true;
    while (!pending.empty()) {
        int node = pending.front();
        pending.pop();
        order.push_back('A' + node);
        for (int next : graph[node]) if (!seen[next]) {
            seen[next] = true;
            pending.push(next);
        }
    }
    return order;
}

int main() {
    vector<vector<int>> graph = {{1, 2}, {3}, {4}, {}, {}};
    vector<char> order = bfs(graph, 0);
    for (size_t i = 0; i < order.size(); i++) {
        if (i) cout << ' ';
        cout << order[i];
    }
    cout << '\n';
}
import java.util.*;

public class Main {
    static List<Character> bfs(List<List<Integer>> graph, int start) {
        Queue<Integer> pending = new ArrayDeque<>();
        boolean[] seen = new boolean[graph.size()];
        List<Character> order = new ArrayList<>();
        pending.add(start);
        seen[start] = true;
        while (!pending.isEmpty()) {
            int node = pending.remove();
            order.add((char) ('A' + node));
            for (int next : graph.get(node)) if (!seen[next]) {
                seen[next] = true;
                pending.add(next);
            }
        }
        return order;
    }

    public static void main(String[] args) {
        List<List<Integer>> graph = List.of(List.of(1, 2), List.of(3), List.of(4), List.of(), List.of());
        List<Character> order = bfs(graph, 0);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < order.size(); i++) {
            if (i > 0) sb.append(' ');
            sb.append(order.get(i));
        }
        System.out.println(sb);
    }
}
Watch it run

Step through it

Running on edges A→B, A→C, B→D, C→E; breadth-first search from A

adjacency list: 5 lists, 4 entriesABCDEadjacency listABCBDCEDnoneEnonespace O(V + E)
Step 1

Store the graph as an adjacency list

Five vertices, four directed edges. Each vertex keeps a list of the vertices its edges point to, so the lists hold 4 entries in total. Space is V + E = 9 items, and a vertex's neighbours are read in time proportional to how many it has.

Output
1 / 14
4

Traversal, and the Visited Set

Two searches underlie almost every graph algorithm, and they differ in one thing: which discovered vertex is handled next.

Breadth-first search uses a queue. It handles every vertex one edge away, then every vertex two edges away, spreading in rings from the start. Depth-first search uses a stack, usually the call stack through recursion. It follows one path as far as it goes, then backs up and tries the next branch.

BFS gives shortest paths in edge count and works level by level. DFS finds cycles, produces topological orders and finds components. DFS memory grows with the length of the current path; BFS memory grows with the widest ring.

The visited set is not an optimisation; it is what makes the search stop. A graph can contain cycles, and without marks the search goes round them forever. Mark a vertex when it is first discovered and queued, not when it is taken out. Marking late lets one vertex enter the queue once for every edge that reaches it.

On an adjacency list both searches run in O(V + E): each vertex is handled once and each edge looked at once (twice in an undirected graph, where every edge sits in two lists).

BFS finds shortest paths only when all edges cost the same. Because the queue is first in, first out, the first time a vertex comes out no shorter route can exist. With weights that argument fails, since two cheap edges can beat one expensive one; Dijkstra's algorithm replaces the queue with a priority queue ordered by distance. More searches are collected under graph algorithms.

  • A search from one vertex reaches only its component; loop over all vertices to cover every one
  • Recursive DFS on a long path can overflow the stack; an explicit stack avoids it
  • Swapping BFS's queue for a stack gives a DFS order, but recursion is the usual DFS
  • Practice: BFS of Graph, DFS of Graph, Number of Islands (a grid as a graph), Clone Graph