Graph, step by step.

A graph is a data structure made of vertices, also called nodes, and edges that join pairs of them; it models networks such as roads, friendships and task dependencies. In code it is usually stored as an adjacency matrix or an adjacency list. This page explains how it works, with step-by-step animations that build the VisiGrab app's example graphs edge by edge, beside their adjacency matrices and adjacency lists.

How a graph works

What is a graph in data structures?

A graph is a set of vertices, also called nodes, and a set of edges, each joining a pair of vertices. It is written G = (V, E); V and E also stand for the number of vertices and edges. Its vertices form no sequence: each can link to any number of others, so a graph is a non-linear data structure. As in the app, vertices here are lettered; textbooks often number them from 0.

Graph terminology: neighbor, degree, path, cycle, connected

  • Adjacent, or neighbors: joined by an edge. With a directed edge A→B, B is a neighbor of A: A's matrix row and list record B, but B's do not record A.
  • Degree: the number of edges at a vertex. Each edge has two ends, so the degrees add up to 2E. In a directed graph, the in-degree counts incoming edges and the out-degree outgoing ones; each kind adds up to E.
  • Path: a sequence of vertices, each joined to the next by an edge, with no vertex repeated. A cycle is a path plus one edge back to its start. An undirected cycle needs at least three vertices: A–B–A reuses one edge.
  • Connected: every vertex can reach every other; otherwise the graph splits into connected components. A directed graph is strongly connected if this holds along the arrows, weakly connected if it holds with the arrows ignored.
  • Simple graph: no self-loops and no parallel edges. All graphs here are simple.

Directed vs undirected graph

In an undirected graph an edge works both ways, like a friendship or a two-way road. In a directed graph, or digraph, A→B leads only from A to B, like following an account or a one-way street.

Two copies of a four-vertex diamond, with A on the left, B at the top, C at the bottom and D on the right. The left copy joins A–B, A–C, B–D and C–D with plain lines. The right copy draws the same four edges as arrows: A to B, A to C, B to D and C to D.
The same four edges, undirected on the left and directed on the right: A–B leads both ways, A→B only from A to B.

Weighted vs unweighted graph: distance, cost and negative weights

In an unweighted graph an edge is simply there or not. In a weighted graph each edge carries a number: a distance, a cost or a time. A weight can be 0 or negative. Dijkstra's shortest-path algorithm needs non-negative weights. Bellman-Ford accepts negative ones and detects a negative cycle.

Cycles and directed acyclic graphs (DAG)

A directed acyclic graph, or DAG, is a directed graph with no cycle: following the arrows never leads back to the start. DAGs model dependencies: project tasks, course prerequisites, build steps, git history.

Two directed triangles on the vertices A, B and C. On the left, arrows run from A to B, from B to C and from C back to A, forming a cycle. On the right, arrows run from A to B, from B to C and from A to C, so no path of arrows returns to its start.
Following the arrows on the left leads from A back to A; with C→A reversed to A→C, the graph on the right is a DAG.

On the left, A must come before B, B before C and C before A: impossible. Reversing C→A to A→C leaves a DAG with one order, A, B, C. An order in which every edge points forward is a topological order, and only a DAG has one.

Sparse vs dense graph: the maximum number of edges

A simple undirected graph has at most V(V − 1) / 2 edges; a directed one has at most V(V − 1). A dense graph has close to the maximum, a sparse graph far fewer: E ≪ V2.

The six vertices A to F drawn twice, with A on the left, B and C along the top, D and E along the bottom and F on the right. The left graph has 5 edges: A–B, B–C, C–F, A–D and D–E. The right graph has 13 edges: every pair of vertices except A–F and B–E.
Six vertices allow at most 15 edges: the sparse graph on the left has 5 and is a tree, the dense one on the right has 13.

Tree vs graph: is a tree a graph?

Yes. A tree is a connected graph with no cycles, so exactly one path joins any two vertices. A tree with n vertices has n − 1 edges. The sparse graph above is a tree, and any added edge closes a cycle: B–D closes A–B–D–A. A binary search tree, a B-tree and a trie are rooted trees: one vertex is the root, and rules fix where each key goes.

Graph representations: adjacency matrix and adjacency list

A graph is usually stored as an adjacency matrix or an adjacency list, shown here for the undirected diamond A–B, A–C, B–D, C–D.

The undirected diamond with edges A–B, A–C, B–D and C–D, above its 4 by 4 adjacency matrix, with rows A 0 1 1 0, B 1 0 0 1, C 1 0 0 1 and D 0 1 1 0, and its adjacency list beside the matrix: A: B, C; B: A, D; C: A, D; D: B, C.
Each undirected edge sets two cells of the matrix and appears in two lists: 8 ones and 8 list entries for 4 edges.

Adjacency matrix: rows, columns and symmetry

An adjacency matrix is a V × V array. Cell (u, v) is 1 if there is an edge from u to v and 0 if not: row = from, column = to. An undirected edge sets two cells, (u, v) and (v, u), so the matrix is symmetric. The diagonal is 0, as a simple graph has no self-loops. A row sum gives a vertex's degree, or its out-degree if the graph is directed; a column sum gives its in-degree. In the diamond, row A reads 0 1 1 0: degree 2.

Adjacency list: the neighbors of each vertex

An adjacency list stores each vertex's neighbors in a list, kept in an array or a map keyed by vertex. An undirected edge goes into both endpoints' lists, 2E entries in total; a directed edge goes only into its start vertex's list, E entries. Here each neighbor is appended as its edge is added; other code sorts the lists, as the app's pictures do, or inserts at the front. The list order decides the order in which DFS and BFS visit neighbors.

Building an undirected graph step by step: adjacency matrix and list

In the player, the six vertices A to F get the 10 edges of the app's first MST example, without weights, one at a time. The result has 20 cells set to 1 and 20 list entries, 2E, and C's list reads B, F, E, D, the order its edges were added.

Build an undirected graph

All steps as text
  1. Six vertices, A to F, and no edges: every cell is 0 and every list is empty. Step forward to add the edges.
  2. Add edge A–B: cells (A, B) and (B, A) become 1, and A and B join each other's lists.
  3. Add edge B–C: cells (B, C) and (C, B) become 1, and B and C join each other's lists.
  4. Add edge A–D: cells (A, D) and (D, A) become 1, and A and D join each other's lists.
  5. Add edge D–E: cells (D, E) and (E, D) become 1, and D and E join each other's lists.
  6. Add edge C–F: cells (C, F) and (F, C) become 1, and C and F join each other's lists.
  7. Add edge E–F: cells (E, F) and (F, E) become 1, and E and F join each other's lists.
  8. Add edge B–D: cells (B, D) and (D, B) become 1, and B and D join each other's lists.
  9. Add edge C–E: cells (C, E) and (E, C) become 1, and C and E join each other's lists.
  10. Add edge B–E: cells (B, E) and (E, B) become 1, and B and E join each other's lists.
  11. Add edge C–D: cells (C, D) and (D, C) become 1, and C and D join each other's lists.
  12. The graph is built: 10 edges, so 20 cells hold 1 and the lists hold 20 entries, two per edge.
Build an undirected graph. Last step: The graph is built: 10 edges, so 20 cells hold 1 and the lists hold 20 entries, two per edge.

Adjacency matrix and list of a directed graph

In the player, the same pairs get the directions of the app's first Dijkstra example. Each edge sets one cell, so the matrix is not symmetric. F has no outgoing edge: its row is all 0 and its list is empty, though its column holds two 1s.

Build a directed graph

All steps as text
  1. The same six vertices and no edges: every cell is 0 and every list is empty. Step forward to add the directed edges.
  2. Add edge A→B: cell (A, B) becomes 1, and B joins A's list.
  3. Add edge B→C: cell (B, C) becomes 1, and C joins B's list.
  4. Add edge A→D: cell (A, D) becomes 1, and D joins A's list.
  5. Add edge E→D: cell (E, D) becomes 1, and D joins E's list.
  6. Add edge C→F: cell (C, F) becomes 1, and F joins C's list.
  7. Add edge E→F: cell (E, F) becomes 1, and F joins E's list.
  8. Add edge D→B: cell (D, B) becomes 1, and B joins D's list.
  9. Add edge C→E: cell (C, E) becomes 1, and E joins C's list.
  10. Add edge B→E: cell (B, E) becomes 1, and E joins B's list.
  11. Add edge D→C: cell (D, C) becomes 1, and C joins D's list.
  12. The graph is built: 10 edges, so 10 cells hold 1 and the lists hold 10 entries, one per edge. F has no outgoing edge, so its row is all 0 and its list is empty.
Build a directed graph. Last step: The graph is built: 10 edges, so 10 cells hold 1 and the lists hold 10 entries, one per edge. F has no outgoing edge, so its row is all 0 and its list is empty.

Weighted adjacency matrix: ∞ for a missing edge

In a weighted graph a cell holds the edge's weight, and a list entry holds a (neighbor, weight) pair. A missing edge is marked ∞, not 0, because 0 can be a real weight. In the player, the directed graph above gets the weights of the same Dijkstra example: all 36 cells start at ∞, and each edge writes its weight into one.

Build a weighted graph

All steps as text
  1. The same six vertices and no edges: every cell is ∞, the diagonal included, and every list is empty. Step forward to add the weighted edges.
  2. Add edge A→B with weight 5: cell (A, B) changes from ∞ to 5, and the pair (B, 5) joins A's list.
  3. Add edge B→C with weight 4: cell (B, C) changes from ∞ to 4, and the pair (C, 4) joins B's list.
  4. Add edge A→D with weight 8: cell (A, D) changes from ∞ to 8, and the pair (D, 8) joins A's list.
  5. Add edge E→D with weight 4: cell (E, D) changes from ∞ to 4, and the pair (D, 4) joins E's list.
  6. Add edge C→F with weight 15: cell (C, F) changes from ∞ to 15, and the pair (F, 15) joins C's list.
  7. Add edge E→F with weight 7: cell (E, F) changes from ∞ to 7, and the pair (F, 7) joins E's list.
  8. Add edge D→B with weight 9: cell (D, B) changes from ∞ to 9, and the pair (B, 9) joins D's list.
  9. Add edge C→E with weight 2: cell (C, E) changes from ∞ to 2, and the pair (E, 2) joins C's list.
  10. Add edge B→E with weight 12: cell (B, E) changes from ∞ to 12, and the pair (E, 12) joins B's list.
  11. Add edge D→C with weight 4: cell (D, C) changes from ∞ to 4, and the pair (C, 4) joins D's list.
  12. The graph is built: 10 edges, so 10 cells hold a weight and every other cell stays ∞, the diagonal included.
Build a weighted graph. Last step: The graph is built: 10 edges, so 10 cells hold a weight and every other cell stays ∞, the diagonal included.

Like the app's Graph Constructor, this page puts ∞ on the diagonal too. Textbooks differ: a distance matrix, as in Floyd–Warshall, has 0 there.

Edge list representation

An edge list stores only the edges, as (u, v, w) triples, in O(E) space. Checking an edge or listing neighbors scans the whole list. It suits algorithms that sort or sweep every edge: Kruskal's MST sorts the edges by weight, and Bellman-Ford relaxes all of them in each round.

Graph data structure time and space complexity

Here deg(u) is the degree of vertex u.

OperationAdjacency matrixAdjacency list
SpaceO(V2)O(V + E)
Check an edge (u, v)O(1)O(deg(u))
List the neighbors of uO(V)O(deg(u))
Visit every edgeO(V2)O(V + E)
Add an edgeO(1)O(1)
Remove an edge (u, v)O(1)O(deg(u) + deg(v))
Add a vertexO(V2)O(1)
Remove a vertexO(V2)O(V + E)

A new vertex means copying the matrix into a larger one. DFS and BFS take O(V + E) with an adjacency list, since the degrees add up to 2E. With a matrix they take O(V2): finding one vertex's neighbors reads a whole row of V cells, however few edges there are.

Adjacency matrix vs adjacency list: which to use

Use a matrix for dense or small graphs, or when most queries ask whether an edge exists. Use a list for sparse graphs and for traversals. Most real graphs are sparse. A road map with 10,000 junctions and 15,000 two-way roads needs 100 million cells as a matrix: 400 MB at 4 bytes a cell. As lists, it needs 30,000 entries and 10,000 list heads: about 160 KB.

Graph implementation in Python, Java and C++

The app's topological-sort code builds an adjacency list from an edge list, as a map from each vertex to a list of neighbors: a dict of lists in Python, a HashMap<Vertex, List<Vertex>> in Java and a std::unordered_map<Vertex, std::vector<Vertex>> in C++. Each edge appends its destination to its source's list.

The full source code is on GitHub, in Python, Java and C++.

Where graphs are used: real-world examples

  • Social networks: friendship is undirected, following is directed.
  • Maps and navigation: Dijkstra's algorithm finds shortest routes, taking the nearest vertex next from a priority queue, usually a min-heap.
  • Computer networks and the web: devices and pages joined by links.
  • Scheduling and builds: tasks and dependencies form a DAG, put in order by topological sort.
  • Network design: Prim's or Kruskal's algorithm finds a minimum spanning tree, joining every vertex at the least total weight.

Three graphs here.
Your own in the app.

In VisiGrab you draw your own graph, see its matrix, and run the algorithms on it step by step.

Your own graph

Tap to add vertices, drag between them to add edges, set their weights. Directed or undirected, up to 12 vertices.

Its adjacency matrix

One tap shows the matrix of the graph you drew: 0 and 1, or weights and ∞.

Algorithms on it

DFS, BFS, Prim, Kruskal, Dijkstra, Bellman-Ford and topological sort, step by step, on your own graph.

Graph theory, illustrated

Vertices and edges, the kinds of graphs, the adjacency matrix and list, with pictures.

Python, Java and C++

Code for DFS, BFS, Dijkstra, Prim, Kruskal and more, explained part by part.

Quizzes

Graph basics in the DFS quiz, and a quiz for every graph algorithm.

Draw a graph
edge by edge.

Download VisiGrab, draw your own graph, and run DFS, BFS, Dijkstra and more on it step by step.

The graph is one of 30+ topics. See them all