AlgoViz

Introduction to graphs

easy 18 min

A graph is a set of vertices joined by edges, directed or undirected, weighted or not.

Video lesson · Chapter 1 of 7

Who can receive the message?

0:00 / 6:12

Graph fundamentals — The two-ferry shortcut

1:27Reel

Read caption

Kiko finds a route between two islands that look adjacent on a paper chart. Follow three ferry lines into an adjacency list. Dots are places. Lines are rides. A path is a chain of rides.

How it works

Step through the idea, or press Play.

Step 1 of 3

Name the parts. Vertices are the things, edges are the connections between pairs of them

Understand it

Start here

What a graph is

A graph is a set of vertices (also called nodes) and a set of edges, each joining a pair of vertices. That is all. Unlike a list or a tree, there is no first item, no root and no fixed shape: anything can connect to anything, which is why graphs model so much of the real world.

The formal definition

G=(V,E),E⊆{ {u,v}:u,v∈V, u≠v },∣V∣=V, ∣E∣=EG = (V, E), \qquad E \subseteq \{\, \{u, v\} : u, v \in V,\ u \neq v \,\}, \qquad \lvert V \rvert = V,\ \lvert E \rvert = E
A graph is a pair: the vertex set and the edge set. In complexity formulas we write VV for the number of vertices and EE for the number of edges.
  • Social networks

    People are vertices, friendships are edges. "People you may know" is a question about neighbours of neighbours.

  • Maps and navigation

    Junctions are vertices, roads are edges, and travel time is a weight on each edge.

  • Computer networks

    Devices are vertices, cables and links are edges. Is the network still in one piece after a failure?

  • Dependencies

    Tasks or courses are vertices, "must come before" is a directed edge. Build tools and schedulers live here.

Vocabulary

Vertices, edges, neighbours and degree

A triangle: three vertices, three edges

Vertices A, B, C. Edges A-B, A-C, B-C. Every vertex is adjacent to the other two, so each has degree 2.
TermMeaningIn the triangle
Vertex (node)A basic unit; it can carry dataA, B, C
EdgeA connection between two verticesA-B, A-C, B-C
Adjacent / neighbourJoined by one edgeB and C are neighbours of A
Degree deg⁡(v)\deg(v)Number of edges touching vvdeg⁡(A)=2\deg(A) = 2
Self-loopAn edge from a vertex to itselfnone
Simple graphNo self-loops, no repeated edgesyes
Interview graphs are simple unless the problem says otherwise. Ask if you are not sure.

Edge types

Directed, undirected and weighted

  • Undirected

    Edges go both ways. If A connects to B, B connects to A. Written {A,B}\{A, B\} or A — B. Example: Facebook friendships.

  • Directed (digraph)

    Each edge is an arrow. A→BA \to B does not mean B→AB \to A. Written (A,B)(A, B). Examples: Twitter follows, web links.

  • Weighted

    Each edge carries a number: a distance, a cost, a time. Either kind of graph can be weighted.

A directed cycle and a weighted road map

Left: A → B → C → A, a directed cycle; from B you cannot step straight back to A. Right: the cheapest Home-to-Station route is via the Mall, 2 + 1 = 3, not via the Park, 4 + 5 = 9.

Counting

Degree and the handshake lemma

Add up every vertex's degree and you always get twice the number of edges. Each edge has two ends and adds 1 to the degree of each, so it is counted exactly twice. It is called the handshake lemma because at a party the total of everyone's handshake counts is twice the number of handshakes.

Handshake lemma (undirected)

∑v∈Vdeg⁡(v)=2∣E∣\sum_{v \in V} \deg(v) = 2\lvert E \rvert
Triangle: 2+2+2=6=2×32 + 2 + 2 = 6 = 2 \times 3. The five-vertex graph in the visualizer: 2+3+2+3+2=12=2×62 + 3 + 2 + 3 + 2 = 12 = 2 \times 6.

Directed version: in-degree and out-degree

∑v∈Vdeg⁡−(v)=∑v∈Vdeg⁡+(v)=∣E∣\sum_{v \in V} \deg^{-}(v) = \sum_{v \in V} \deg^{+}(v) = \lvert E \rvert
In-degree deg⁡−(v)\deg^{-}(v) counts arrows arriving, out-degree deg⁡+(v)\deg^{+}(v) counts arrows leaving. Each arrow has one tail and one head, so both totals equal the number of edges.

Limits

How many edges can a graph have?

Maximum edges in a simple graph

Emax⁡undirected=(V2)=V(V−1)2,Emax⁡directed=V(V−1),so E=O(V2)E_{\max}^{\text{undirected}} = \binom{V}{2} = \frac{V(V-1)}{2}, \qquad E_{\max}^{\text{directed}} = V(V-1), \qquad \text{so } E = O(V^2)
Each of the VV vertices can join the other V−1V - 1. Undirected counts each pair once, hence the division by 2. A graph with every possible edge is called complete.
KindEdgesExampleBest representation
SparseEE close to VVRoad maps, social networks, the webAdjacency list
DenseEE close to V2V^2Small complete graphs, flight tablesMatrix is fine
Treeexactly V−1V - 1File systems, org chartsAdjacency list
CompleteV(V−1)/2V(V-1)/2Every pair of cities joinedMatrix
Most real graphs are sparse: a person has hundreds of friends, not billions.

Structure

Paths, cycles and connected components

TermMeaning
PathA sequence of vertices where each consecutive pair is joined by an edge. Its length is the number of edges.
Simple pathA path that never repeats a vertex.
CycleA path of length 3 or more that starts and ends at the same vertex without reusing an edge.
ConnectedEvery vertex can reach every other by some path (undirected).
Connected componentA maximal group of vertices that can all reach each other.
Strongly connectedDirected version: every vertex can reach every other following the arrows.

One graph, two connected components

Five vertices, four edges, two components. A traversal from A reaches A, B and C only; X and Y need a second traversal. A-B-C-A is a cycle.

Special shapes

Trees and DAGs are graphs too

  • Tree

    Connected and no cycles. Always exactly V−1V - 1 edges, and exactly one path between any two vertices. See binary tree.

  • DAG

    Directed acyclic graph: arrows, no directed cycle. Models task scheduling and course prerequisites; it has a topological order.

  • Bipartite

    Vertices split into two sides with every edge crossing between them, so two colours suffice. Used for matching problems.

  • Implicit graph

    A grid is a graph: each cell is a vertex, its up, down, left and right cells are its edges. See matrix DFS.

Tree test

G is a tree  ⟺  G is connected and ∣E∣=∣V∣−1  ⟺  G is connected and acyclicG \text{ is a tree} \iff G \text{ is connected and } \lvert E \rvert = \lvert V \rvert - 1 \iff G \text{ is connected and acyclic}
Any two of connected, acyclic and E=V−1E = V - 1 imply the third. The Graph Valid Tree problem checks E=V−1E = V - 1 and then one traversal for connectivity.

Course prerequisites form a DAG

No arrow leads back to a course you already passed, so a valid order exists: Python, Data structures, Math, Algorithms, Machine learning. Add ML → Python and the cycle makes every order impossible.

Representations

Three ways to store a graph

RepresentationThe square graph 0-1, 0-2, 1-3, 2-3Space
Edge list[(0,1), (0,2), (1,3), (2,3)]O(E)O(E)
Adjacency list0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]O(V+E)O(V + E)
Adjacency matrix[[0,1,1,0], [1,0,0,1], [1,0,0,1], [0,1,1,0]]O(V2)O(V^2)
The edge list is how problems hand you the input. Convert it to an adjacency list before you traverse.

From input to something you can walk

On a matrix, finding a vertex's neighbours scans a whole row, so a full traversal costs O(V2)O(V^2) instead of O(V+E)O(V + E).
Python
edges = [(0, 1), (0, 2), (1, 3), (2, 3)]n = 4# 1. Edge list: the input itselfprint("Edge list:", edges)# 2. Adjacency list: O(V + E) spaceadj = [[] for _ in range(n)]for u, v in edges:    adj[u].append(v)    adj[v].append(u)          # undirected: both directionsprint("Adjacency list:")for i, nbs in enumerate(adj):    print(f"  {i}: {nbs}")# 3. Adjacency matrix: O(V^2) spacematrix = [[0] * n for _ in range(n)]for u, v in edges:    matrix[u][v] = 1    matrix[v][u] = 1          # symmetricprint("Adjacency matrix:")for row in matrix:    print(" ", row)print("has edge 1-3?", matrix[1][3] == 1, 3 in adj[1])print("degrees:", [len(nbs) for nbs in adj])   # [2, 2, 2, 2]
Build all three from the same edges.
Edit and run it in your browser

Costs

Adjacency list versus matrix

Where the space goes

list=V⏟one list per vertex+∑vdeg⁡(v)⏟=2E=O(V+E),matrix=V×V=O(V2)\text{list} = \underbrace{V}_{\text{one list per vertex}} + \underbrace{\sum_{v} \deg(v)}_{= 2E} = O(V + E), \qquad \text{matrix} = V \times V = O(V^2)
Square graph: the list stores 4+8=124 + 8 = 12 entries, the matrix 1616 cells. With V=105V = 10^5 and E=2×105E = 2 \times 10^5 the list holds about 5×1055 \times 10^5 entries while the matrix needs 101010^{10} cells.
OperationAdjacency listAdjacency matrixNote
SpaceO(V+E)O(V + E)O(V2)O(V^2)List wins on sparse graphs
Add vertexO(1)O(1)O(V2)O(V^2)Matrix must be rebuilt one size bigger
Add edgeO(1)O(1)O(1)O(1)Both constant
Has edge (u,v)(u, v)O(deg⁡(u))O(\deg(u))O(1)O(1)Neighbour sets make the list O(1)O(1) average
Get neighbours of vvO(1)O(1) to fetch, O(deg⁡(v))O(\deg(v)) to walkO(V)O(V)Matrix scans a full row
Remove edgeO(deg⁡(u)+deg⁡(v))O(\deg(u) + \deg(v))O(1)O(1)List searches both lists
Remove vertexO(V+E)O(V + E)O(V2)O(V^2)Both expensive
Full DFS / BFSO(V+E)O(V + E)O(V2)O(V^2)Why interviews use lists

Use an adjacency list when

  • The graph is sparse, EE much smaller than V2V^2 (nearly always).
  • You iterate neighbours, as every BFS and DFS does.
  • Memory matters or VV is large.
  • The input is an edge list, as in most interview problems.

Use an adjacency matrix when

  • The graph is small or dense, EE close to V2V^2.
  • You need many O(1)O(1) "is there an edge?" checks.
  • The algorithm is matrix-shaped, like Floyd-Warshall all-pairs shortest paths.
  • Weights fit naturally in cells, matrix[u][v] = w.

Traversal

Walking a graph: DFS and BFS with a visited set

The two traversals you know from trees work on graphs with one addition: a visited set. A tree has no cycles, so you never meet a node twice; a graph can lead you back to where you started. Tree DFS dives deep along one path, tree BFS spreads out ring by ring, and the grid versions are matrix DFS and matrix BFS.

The traversal loop with a visited set

Container = stack (or recursion) for DFS, queue for BFS. Everything else is identical.
Python
from collections import dequeedges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 3), (3, 4)]adj = [[] for _ in range(5)]for u, v in edges:    adj[u].append(v)    adj[v].append(u)def dfs(u, visited, order):    visited.add(u)    order.append(u)    for v in adj[u]:        if v not in visited:          # without this: infinite recursion            dfs(v, visited, order)    return orderdef bfs(start):    visited, queue, order = {start}, deque([start]), []    while queue:        u = queue.popleft()        order.append(u)        for v in adj[u]:            if v not in visited:                visited.add(v)        # mark when enqueued                queue.append(v)    return orderprint("DFS:", dfs(0, set(), []))   # [0, 1, 3, 2, 4]print("BFS:", bfs(0))              # [0, 1, 2, 3, 4]
DFS and BFS on the five-vertex graph from the visualizer.
Edit and run it in your browser
DFS (depth-first)BFS (breadth-first)
ContainerStack or recursionQueue (deque)
OrderGoes deep before wideGoes wide before deep
Good forPaths, cycles, components, topological sortFewest edges, nearest target, levels
TimeO(V+E)O(V + E)O(V+E)O(V + E)
Extra spaceO(V)O(V) visited plus up to O(V)O(V) recursionO(V)O(V) visited plus up to O(V)O(V) queue
On a tree DFS uses O(h)O(h) and BFS O(w)O(w) space. On a general graph both can grow to O(V)O(V).

Pattern spotting

Recognising a graph problem

The shape of almost every graph solution
  1. 1Read n and edgesDirected? Weighted?
  2. 2Build adjacency listBoth directions if undirected
  3. 3Pick a traversalDFS, BFS or Dijkstra
  4. 4Visit with a setEach vertex once
  5. 5Loop all verticesCover every component

Steps 2 and 4 are the same in nearly every problem; the thinking goes into step 3 and what you record while visiting.

Clue in the problemGraph viewExample problems
"connections", "friends", "network"Undirected graph, count componentsNumber of provinces, connected components
"depends on", "prerequisite", "before"Directed graph, detect cycles, topological sortCourse schedule, task order
Grid of land and waterImplicit graph, 4-directional neighboursNumber of islands, flood fill
"fewest steps", "minimum moves"Unweighted graph, BFSWord ladder, open the lock
"cheapest", "fastest", costs on edgesWeighted graph, DijkstraNetwork delay time
Copy or serialise a graphTraversal plus old-to-new mapClone graph

Which traversal?

Three-state colouring: white = unvisited, grey = on the current path, black = finished. Meeting a grey vertex means a directed cycle.

Recap

Key takeaways

Key points

  • A graph G=(V,E)G = (V, E) is vertices plus edges. Edges can be directed or undirected, weighted or unweighted.
  • Degree counts a vertex's edges, and ∑deg⁡(v)=2E\sum \deg(v) = 2E; in a digraph in-degrees and out-degrees each sum to EE.
  • A simple graph has at most V(V−1)/2V(V-1)/2 undirected or V(V−1)V(V-1) directed edges. Real graphs are usually sparse.
  • Trees (connected, acyclic, V−1V - 1 edges), DAGs and grids are all special graphs.
  • Adjacency list: O(V+E)O(V + E) space and O(deg⁡)O(\deg) neighbours, the default. Matrix: O(V2)O(V^2) space and O(1)O(1) edge checks, for small dense graphs.
  • DFS and BFS on a graph need a visited set; both run in O(V+E)O(V + E) on an adjacency list. Start a new traversal from every unvisited vertex to cover all components.

Sources