Lesson 6 · Graphs and Trees

Unweighted Shortest Path

When every edge costs the same, the shortest path is the one with the fewest edges, and one breadth-first search finds it for every vertex at once. Two arrays do the work: dist[] for how far each vertex is, parent[] for how to get there.

Unweighted Shortest Path concept diagramTwo arrays indexed by vertex 0 to 6 after breadth-first search from vertex 0: parent is none, 0, 0, 0, 1, 2, 4 and dist is 0, 1, 1, 1, 2, 2, 3. Curved arrows above the parent row jump from cell 6 to cell 4, from cell 4 to cell 1 and from cell 1 to cell 0, the source. Below, the walk reversed reads 0, 1, 4, 6: a shortest path with 3 edges, equal to dist[6].follow parent[] from the target until the sourceparentdistvertex–00011012013124225436parent[6] = 4parent[4] = 1parent[1] = 0reversed01463 edges = dist[6]walk back 6 → 4 → 1 → 0, reverse it: the shortest path from 0 to 6
1

Fewest Edges Is Shortest

A graph is unweighted when its edges carry no cost, or all carry the same cost. The length of a path is then just its number of edges, and the unweighted shortest path from a source s to a vertex v is a path with the fewest edges. Its length is the distance dist(s, v).

This is the plain version of the shortest-path problem, and it has the plain answer: breadth-first search from s. BFS reaches vertices in order of distance, so the first time it reaches v, it has used as few edges as possible. One run answers the question for every vertex at once, which is why the problem is usually stated as single-source.

The same idea covers far more than drawn graphs. A maze is a graph of cells, a word puzzle is a graph of words one letter apart, a lock is a graph of codes one turn apart. Whenever each move costs one, finding the fewest moves is a shortest path in unweighted graph problem.

  • Length of a path = number of edges
  • Directed or undirected both work; follow only the edges that exist
  • Answer for one source and every target comes from one BFS
2

BFS With a Distance and a Parent Array

  1. Set dist[s] = 0 and put s in a queue
  2. Take u from the front of the queue
  3. For each neighbour v of u with dist[v] = -1: set dist[v] = dist[u] + 1, set parent[v] = u, and add v to the back
  4. Repeat until the queue is empty, or stop as soon as the target is reached if only one target matters
  5. Any vertex still at -1 cannot be reached from s

The search keeps two arrays indexed by vertex. dist[v] starts at -1 (unknown) for everything except the source. parent[v] records the vertex that first reached v.

  • Time O(V + E) on an adjacency list: each vertex is queued once, each edge checked once per end
  • Extra space O(V) for dist, parent and the queue
  • dist[v] = -1 doubles as the seen mark, so no separate visited set is needed
3

Why the First Distance Is Final

The queue only ever holds vertices at two distances, d and d + 1, with every d in front. So vertices leave in order of distance, and every vertex at distance d is expanded before any vertex at distance d + 1.

Now take a vertex v first reached from u, so dist[v] = dist[u] + 1. A shorter route to v would end at some neighbour w closer to s than u. w would have left the queue before u and reached v first. It did not, so no shorter route exists and the first value BFS writes is final. Exam questions on the shortest distance in unweighted graph want this argument; the full version is worked through in the breadth-first search lesson.

This is also why BFS never needs to lower a distance. Later edges into v can only tie the first value, never beat it. Weighted algorithms such as Dijkstra's algorithm must keep updating distances; this one writes each one once.

  • Queue holds distances d and d + 1 only, in that order
  • A later edge into v can tie its distance but not lower it
  • Each dist[v] is written once and is final when written
Key reference

Terms, operations, and practical uses

Key terms

  • DistanceThe number of edges on a shortest path from the source.
  • Parent arrayFor each vertex, the vertex that first reached it in the BFS.
  • BFS treeThe edges from each vertex to its parent; every route down it is shortest.
  • Edge splittingTurning a weight-k edge into k unit edges so BFS applies.
Implementation

Code in Python, C++ and Java

from collections import deque


def bfs(n, edges, source):
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        adj[v].append(u)
    dist = [-1] * n
    parent = [-1] * n
    ways = [0] * n
    dist[source], ways[source] = 0, 1
    q = deque([source])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if dist[v] == -1:
                dist[v] = dist[u] + 1
                parent[v] = u
                q.append(v)
            if dist[v] == dist[u] + 1:
                ways[v] += ways[u]
    return dist, parent, ways


def path_to(parent, dist, target):
    if dist[target] == -1:
        return []
    path = []
    while target != -1:
        path.append(target)
        target = parent[target]
    return path[::-1]


edges = [(0, 1), (0, 2), (0, 3), (1, 4), (2, 4), (2, 5), (3, 5), (4, 6), (5, 6)]
dist, parent, ways = bfs(8, edges, 0)
print("dist:", *dist)
print("path 0 -> 6:", *path_to(parent, dist, 6))
print("shortest paths to 6:", ways[6])
print("path 0 -> 7:", *(path_to(parent, dist, 7) or ["none"]))
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

void bfs(int n, const vector<pair<int, int>>& edges, int source,
         vector<int>& dist, vector<int>& parent, vector<long long>& ways) {
    vector<vector<int>> adj(n);
    for (auto [u, v] : edges) {
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    dist.assign(n, -1);
    parent.assign(n, -1);
    ways.assign(n, 0);
    dist[source] = 0;
    ways[source] = 1;
    queue<int> q;
    q.push(source);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v : adj[u]) {
            if (dist[v] == -1) {
                dist[v] = dist[u] + 1;
                parent[v] = u;
                q.push(v);
            }
            if (dist[v] == dist[u] + 1) ways[v] += ways[u];
        }
    }
}

vector<int> pathTo(const vector<int>& parent, const vector<int>& dist, int target) {
    vector<int> path;
    if (dist[target] == -1) return path;
    for (int v = target; v != -1; v = parent[v]) path.push_back(v);
    reverse(path.begin(), path.end());
    return path;
}

void printPath(const string& label, const vector<int>& path) {
    cout << label;
    if (path.empty()) cout << " none";
    for (int v : path) cout << " " << v;
    cout << "\n";
}

int main() {
    vector<pair<int, int>> edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {2, 4}, {2, 5}, {3, 5}, {4, 6}, {5, 6}};
    vector<int> dist, parent;
    vector<long long> ways;
    bfs(8, edges, 0, dist, parent, ways);
    cout << "dist:";
    for (int d : dist) cout << " " << d;
    cout << "\n";
    printPath("path 0 -> 6:", pathTo(parent, dist, 6));
    cout << "shortest paths to 6: " << ways[6] << "\n";
    printPath("path 0 -> 7:", pathTo(parent, dist, 7));
}
import java.util.*;

public class Main {
    static int[] dist, parent;
    static long[] ways;

    static void bfs(int n, int[][] edges, int source) {
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int[] e : edges) {
            adj.get(e[0]).add(e[1]);
            adj.get(e[1]).add(e[0]);
        }
        dist = new int[n];
        parent = new int[n];
        ways = new long[n];
        Arrays.fill(dist, -1);
        Arrays.fill(parent, -1);
        dist[source] = 0;
        ways[source] = 1;
        ArrayDeque<Integer> q = new ArrayDeque<>();
        q.add(source);
        while (!q.isEmpty()) {
            int u = q.poll();
            for (int v : adj.get(u)) {
                if (dist[v] == -1) {
                    dist[v] = dist[u] + 1;
                    parent[v] = u;
                    q.add(v);
                }
                if (dist[v] == dist[u] + 1) ways[v] += ways[u];
            }
        }
    }

    static List<Integer> pathTo(int target) {
        LinkedList<Integer> path = new LinkedList<>();
        if (dist[target] == -1) return path;
        for (int v = target; v != -1; v = parent[v]) path.addFirst(v);
        return path;
    }

    static void printPath(String label, List<Integer> path) {
        StringBuilder sb = new StringBuilder(label);
        if (path.isEmpty()) sb.append(" none");
        for (int v : path) sb.append(" ").append(v);
        System.out.println(sb);
    }

    public static void main(String[] args) {
        int[][] edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {2, 4}, {2, 5}, {3, 5}, {4, 6}, {5, 6}};
        bfs(8, edges, 0);
        StringBuilder sb = new StringBuilder("dist:");
        for (int d : dist) sb.append(" ").append(d);
        System.out.println(sb);
        printPath("path 0 -> 6:", pathTo(6));
        System.out.println("shortest paths to 6: " + ways[6]);
        printPath("path 0 -> 7:", pathTo(7));
    }
}
Watch it run

Step through it

Running on edges 0–1 0–2 0–3 1–4 2–4 2–5 3–5 4–6 5–6, source 0

take the front of the queue · each unseen neighbour gets dist + 1 and a parent0123456vDISTPARENT00–1∞–2∞–3∞–4∞–5∞–6∞–QUEUEfront0unknown = not reached yet; the queue holds vertices waiting to be expanded
Step 1

Start: only the source is known

Every edge counts as one step, so the shortest path is the one with the fewest edges. dist[0] = 0 because the source is zero steps from itself. Every other distance is unknown (∞) and has no parent yet. The queue holds just 0.

Output
1 / 15
4

Printing the Path

dist[] gives the length; parent[] gives the route. Start at the target t and follow parent[t], parent[parent[t]] and so on until the source, whose parent is empty. That lists the path backwards, so reverse it. The walk takes O(length of path) time.

Check dist[t] first. If t was never reached, its parent is empty and the walk would return just [t], which looks like a path but is not one. When t equals s the answer is [s] with distance 0.

The vertices that have a parent, joined to their parents, form a tree rooted at s: the BFS tree. Every root-to-vertex route in it is a shortest path, so one array stores a shortest path to every vertex in O(V) space. When the graph is too large to store, as in an implicit state space, keep the parents in a hash map keyed by state instead.

  • Walk parent[] from the target, then reverse
  • dist[t] = -1 means no path; do not walk
  • parent[] stores one shortest path to every vertex
5

Counting Shortest Paths

Often there is more than one shortest path, and some problems ask for the number of shortest paths from s to t. BFS counts them with a third array. Set ways[s] = 1. Whenever u looks at a neighbour v with dist[v] = dist[u] + 1, add ways[u] to ways[v]. That includes the first discovery and every later tie.

It works because each shortest path to v arrives from some vertex exactly one level up, and every vertex one level up is fully counted before v is expanded. Edges between vertices on the same level, or back up a level, are on no shortest path and add nothing.

The counts grow fast: on a grid they are binomial coefficients, so use 64-bit integers or take them modulo a prime, as most problems ask. With weights, the same rule runs inside Dijkstra: add when a route ties the best cost, reset when it beats it.

  • ways[s] = 1; ways[v] += ways[u] whenever dist[v] = dist[u] + 1
  • Same-level edges never lie on a shortest path
  • Counts can overflow 32 bits; use 64-bit or a modulus
6

BFS or DFS for Shortest Path?

BFS. Depth-first search follows one branch as far as it goes, so the first time it reaches a vertex is along whatever branch it tried first, which can be far longer than the shortest. Recording DFS depth as distance gives wrong answers, as the tracer shows. To get distances from DFS you would have to explore every path, which is exponential.

Weights break BFS in a different way. BFS still finds the fewest edges, but a route with more edges can cost less. Pick the tool by the edge weights:

Shortest-path method by edge weight
Edge weightsMethodTime
All equalBFSO(V + E)
Only 0 and 10-1 BFS with a dequeO(V + E)
Small positive integersSplit each edge into unit edges, then BFSO(V + total weight)
Any non-negativeDijkstra with a heapO((V + E) log V)
Some negativeBellman–FordO(V · E)
  • DFS finds a path, not the shortest one
  • Edge splitting: a weight-k edge becomes k unit edges through k - 1 new vertices
  • For 0 and 1 weights see 0-1 BFS; for general weights Dijkstra's algorithm
7

Grids, Several Sources and All Pairs

In a grid each open cell is a vertex joined to its 4 (or 8) neighbours, and the graph is never built: generate neighbours on the fly and keep dist in a 2D array. Shortest Path in Binary Matrix and Nearest Exit from Entrance in Maze are exactly this. Word Ladder and Open the Lock do the same on words and lock codes.

With several sources, put all of them in the queue at distance 0. One run then gives each vertex its distance to the nearest source, the trick behind Rotting Oranges and 01 Matrix. It costs one BFS, not one per source.

For distances between every pair of vertices, run BFS from each vertex: O(V · (V + E)) in total. On a sparse graph that beats Floyd–Warshall, which takes O(V³) whatever the edges.

  • Grid: cells are vertices, moves are edges, dist is a 2D array
  • Several sources: all start in the queue at distance 0
  • All pairs on a sparse graph: V runs of BFS