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 graphs work
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Here deg(u) is the degree of vertex u.
| Operation | Adjacency matrix | Adjacency list |
|---|---|---|
| Space | O(V2) | O(V + E) |
| Check an edge (u, v) | O(1) | O(deg(u)) |
| List the neighbors of u | O(V) | O(deg(u)) |
| Visit every edge | O(V2) | O(V + E) |
| Add an edge | O(1) | O(1) |
| Remove an edge (u, v) | O(1) | O(deg(u) + deg(v)) |
| Add a vertex | O(V2) | O(1) |
| Remove a vertex | O(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.
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.
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++.
// in the app
In VisiGrab you draw your own graph, see its matrix, and run the algorithms on it step by step.
Tap to add vertices, drag between them to add edges, set their weights. Directed or undirected, up to 12 vertices.
One tap shows the matrix of the graph you drew: 0 and 1, or weights and ∞.
DFS, BFS, Prim, Kruskal, Dijkstra, Bellman-Ford and topological sort, step by step, on your own graph.
Vertices and edges, the kinds of graphs, the adjacency matrix and list, with pictures.
Code for DFS, BFS, Dijkstra, Prim, Kruskal and more, explained part by part.
Graph basics in the DFS quiz, and a quiz for every graph algorithm.
// build your own
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