Graph - Introduction
What a graph is, the words used to describe one, and how to store one in Java.
A graph is how we draw anything made of things and the connections between them: web pages and the links between them, people and who follows whom, tasks and which one has to finish first. Most of the algorithms in this section start from a picture like the one below, so this page walks through that picture and the words you will meet everywhere else.
Vertices and edges
Look at the picture above. The circles numbered 1, 2, 3 and 4 are the vertices of the graph. Many books call them nodes; both words mean the same thing. The orange circle is vertex 1.
The lines are the edges. An edge joins two vertices and says they are related. The orange line joins vertex 1 and vertex 3, so it is the edge 1-3. Count all the lines and you get five edges: 1-2, 2-3, 3-4, 4-1 and 1-3.
Notice what is missing, too. There is no line between 2 and 4, so those two vertices are not directly connected. To get from 2 to 4 you have to pass through another vertex, such as 1 or 3.
That is all a graph is: a set of vertices and a set of edges between pairs of them. Books write it as G = (V, E), where V is the set of vertices and E is the set of edges. For our picture, V = {1, 2, 3, 4} and E = {1-2, 2-3, 3-4, 4-1, 1-3}.
The lines here have no arrows, so every edge works both ways: you can go from 1 to 3, and from 3 back to 1. A graph like this is called undirected.
The number of edges touching a vertex is its degree. Vertex 1 touches three edges (to 2, 3 and 4), so its degree is 3. Vertex 2 touches two, so its degree is 2.
When edges have a direction
Here are the same four vertices, but now every edge has an arrow. The orange arrow points from 1 to 2: you can follow it from 1 to 2, but not from 2 back to 1. A graph whose edges have arrows is a directed graph.
Directed graphs fit relations that only go one way. "Task 1 must finish before task 2 can start" is an arrow from 1 to 2. So is "page 1 links to page 2", because page 2 does not have to link back.
With arrows, the degree splits in two. Vertex 1 has three arrows leaving it and none arriving, so its outdegree is 3 and its indegree is 0. Vertex 3 has two arrows arriving (from 1 and from 4) and one leaving (to 2), so its indegree is 2 and its outdegree is 1.
When edges have a cost
Sometimes a connection has a cost, such as a distance, a travel time or a price. Writing that number on each edge gives a weighted graph. In the picture, the edge 1-2 has weight 4 and the edge 1-3 has weight 1.
Weights change what "the shortest way" means. Going from 1 to 2 along the direct edge costs 4. The orange route goes from 1 to 3 and then from 3 to 2. It uses two edges instead of one, but it costs only 1 + 2 = 3, so the longer-looking route is the cheaper one. Finding the cheapest route like this is what
Paths and cycles
A path is a way of walking from one vertex to another by following edges. In the left picture, the orange edges trace the path 4, 1, 2, 3: from 4 to 1, then 1 to 2, then 2 to 3.
A cycle is a path that comes back to where it started. In the right picture, the walk from 1 to 2 to 3 and back to 1 is a cycle. A graph with no cycles at all is acyclic.
Directed graphs with no cycles come up so often that they have a short name, DAG (directed acyclic graph). Task dependencies must form a DAG: if task 1 waits for task 2 and task 2 waits for task 1, neither can ever start.
Connected or not
In this picture vertex 2 has lost its edges. You can still walk between 1, 3 and 4, but nothing reaches 2. A graph where every vertex can reach every other vertex is connected, and this one is not. It falls into two connected components: the group 1, 3, 4, and vertex 2 on its own.
One shape is worth knowing by name. A connected undirected graph with no cycles is a tree. The path 4, 1, 2, 3 from the previous section is a tree: it reaches all four vertices, has no cycle, and uses three edges. A tree with n vertices always has exactly n - 1 edges: start from one vertex, and every edge you add to grow the tree brings in exactly one new vertex.
Storing a graph in Java
A program cannot look at a picture, so it needs the edges in a data structure. Problems usually give you the edges as a list of pairs. For our first graph that is {{1, 2}, {2, 3}, {3, 4}, {4, 1}, {1, 3}}
An adjacency list gives every vertex a list of the vertices it is joined to, called its neighbours. An adjacency matrix is a table with one row and one column per vertex, where the cell in row u, column v says whether u and v are joined. Here is the first graph stored both ways:
| Vertex | Adjacency list | Matrix row (columns 1, 2, 3, 4) |
|---|---|---|
| 1 | 2, 4, 3 | 0 1 1 1 |
| 2 | 1, 3 | 1 0 1 0 |
| 3 | 2, 4, 1 | 1 1 0 1 |
| 4 | 3, 1 | 1 0 1 0 |
Read the row for vertex 1. Vertex 1 is joined to 2, 4 and 3, so its list holds those three, and its matrix row has a 1 in columns 2, 3 and 4. Every edge shows up twice, once from each end, because the graph is undirected: the edge 1-3 puts 3 in vertex 1's list and 1 in vertex 3's list. The lists keep the order the edges were given in, which is why vertex 1 lists 4 before 3.
This program builds both from the edge list:
import java.util.*;
public class GraphBasics {
// Adjacency list: neighbours.get(u) holds every vertex joined to u.
static List<List<Integer>> adjacencyList(int n, int[][] edges) {
List<List<Integer>> neighbours = new ArrayList<>();
for (int v = 0; v <= n; v++) {
neighbours.add(new ArrayList<>()); // slot 0 stays empty, vertices are 1..n
}
for (int[] e : edges) {
neighbours.get(e[0]).add(e[1]);
neighbours.get(e[1]).add(e[0]); // undirected: the edge works both ways
}
return neighbours;
}
// Adjacency matrix: joined[u][v] is true when there is an edge between u and v.
static boolean[][] adjacencyMatrix(int n, int[][] edges) {
boolean[][] joined = new boolean[n + 1][n + 1];
for (int[] e : edges) {
joined[e[0]][e[1]] = true;
joined[e[1]][e[0]] = true;
}
return joined;
}
public static void main(String[] args) {
int n = 4;
int[][] edges = {{1, 2}, {2, 3}, {3, 4}, {4, 1}, {1, 3}};
List<List<Integer>> neighbours = adjacencyList(n, edges);
for (int v = 1; v <= n; v++) {
System.out.println("Neighbours of " + v + ": " + neighbours.get(v));
}
boolean[][] joined = adjacencyMatrix(n, edges);
System.out.println("Is 2 joined to 4? " + joined[2][4]);
System.out.println("Is 1 joined to 3? " + joined[1][3]);
}
}
Running it prints the same lists as the table, and answers two questions from the matrix:
Neighbours of 1: [2, 4, 3]
Neighbours of 2: [1, 3]
Neighbours of 3: [2, 4, 1]
Neighbours of 4: [3, 1]
Is 2 joined to 4? false
Is 1 joined to 3? true
Both structures have n + 1 slots because the vertices are numbered from 1, so slot 0 is never used. That keeps joined[4]ArrayIndexOutOfBoundsException
For a weighted graph, keep the weight next to each neighbour. A common way is a list of int[]{neighbour, weight}{2, 4}{4, 7}{3, 1}
List or matrix?
The two structures are quick at different things:
| Question | Adjacency list | Adjacency matrix |
|---|---|---|
| Who are the neighbours of u? | O(degree of u): the list holds exactly them | O(V): scan the whole row |
| Are u and v joined? | O(degree of u): search u's list | O(1): one lookup |
| Memory | O(V + E) | O(V2) |
Memory is where the difference shows. Our small graph needs 16 matrix cells to describe 5 edges, while the lists hold 10 entries, two per edge. A graph with 100,000 vertices would need 10 billion matrix cells, even if each vertex had only a handful of neighbours.
Most graph algorithms, including BFS and DFS, spend their time asking "who are the neighbours of this vertex?", so the adjacency list is the usual choice. A matrix makes sense when the graph is small, or when most pairs of vertices are joined and you often need to check one particular edge.
Grids are graphs too
Many problems give you a 2D grid instead of a list of edges. You can treat each cell as a vertex that is joined to the cells directly above, below, left and right of it. There is no need to build an adjacency list: the neighbours of cell (r, c)(r - 1, c)(r + 1, c)(r, c - 1)(r, c + 1)
Where to go next
Breadth First Search visits the graph one layer at a time, nearest vertices first.Depth First Search follows one path as far as it goes before backing up.Dijkstra's Algorithm finds the cheapest route in a weighted graph, like the 1, 3, 2 route above.Kruskal's Algorithm andPrim's Algorithm pick the cheapest set of edges that keeps every vertex connected.