Lesson 13 · Graphs and Trees

Bridges in a Graph

A bridge is an edge that lies on no cycle, so removing it cuts the graph in two. One depth-first search finds every bridge: for each tree edge u–v, ask whether anything below v has an edge back to u or higher. If nothing does, the edge u–v is the only way out, and it is a bridge.

Bridges in a Graph concept diagramAn undirected graph of 8 vertices: triangle 0, 1, 2; edge 1 to 3; triangle 3, 4, 5; edge 5 to 6; and two parallel edges between 6 and 7. The edges 1 to 3 and 5 to 6 are bridges, drawn in orange. Dashed boxes mark the three pieces left when the bridges are removed: 0, 1, 2; 3, 4, 5; and 6, 7. Below, each piece becomes one node and the bridges join them in a path, the bridge tree.{0, 1, 2}{3, 4, 5}{6, 7}bridgebridge01234567two edges: cut one, the other remainsshrink each box to one node: the bridges are what is left, and they form a tree1–35–6{0, 1, 2}{3, 4, 5}{6, 7}bridges = edges on no cycle · tree edge u–v is one when low[v] > disc[u]
1

An Edge That Lies on No Cycle

In an undirected graph, an edge is a bridge, also called a cut edge, if deleting it increases the number of connected pieces. Its two ends end up on different sides with no other route between them.

That happens exactly when the edge is on no cycle. If u–v is on a cycle, the rest of the cycle is another route from u to v, so removing the edge changes nothing. If it is on no cycle, no such route exists. Every edge of a tree is therefore a bridge, and a single cycle has none.

  • Edge on a cycle: never a bridge
  • Tree with n vertices: all n − 1 edges are bridges
  • Two parallel edges between the same pair: neither is a bridge
2

Brute Force: Remove Each Edge and Look

The definition gives a direct method. For each edge, delete it, run a BFS or DFS from one of its ends, and check whether the other end is still reached. Put the edge back and move on. That is E searches of O(V + E) each, so O(E × (V + E)) in total. A graph with 10,000 vertices and 50,000 edges needs 50,000 full searches; the method below needs one.

3

One Search: Discovery Time and Low Value

  1. Arrive at u: disc[u] = low[u] = counter, then add one to the counter
  2. For each edge to v, skip it if it is the very edge used to arrive at u
  3. v unvisited: visit v, then low[u] = min(low[u], low[v]); if low[v] > disc[u], the edge u–v is a bridge
  4. v already visited: low[u] = min(low[u], disc[v])
  5. Start again from every vertex not yet reached, so every piece of the graph is covered

Run one DFS and number vertices in the order the search reaches them: disc[u]. In an undirected graph every edge the search does not use as a tree edge joins a vertex to one of its own ancestors. There are no cross edges, because the search would have walked such an edge as a tree edge first.

Define low[v] as the smallest disc that v's subtree can reach, using tree edges downward and then at most one non-tree edge. The bridge finding algorithm above is that search plus one comparison for each tree edge u–v, where u is the parent.

  • low[v] > disc[u]: nothing under v reaches u or above, so u–v is the only link
  • low[v] ≤ disc[u]: some edge from v's subtree climbs to u or higher, which closes a cycle through u–v
Key reference

Terms, operations, and practical uses

Key terms

  • BridgeAn edge whose removal disconnects its two ends; an edge on no cycle.
  • low[v]The smallest disc reachable from v's subtree with one non-tree edge.
  • 2-edge-connected componentA largest piece that survives the loss of any one edge.
  • Bridge treeThe 2-edge-connected components as nodes, joined by the bridges.
Implementation

Code in Python, C++ and Java

def find_bridges(n, edges, skip_by_id=True, strict=True):
    adj = [[] for _ in range(n)]
    for i, (u, v) in enumerate(edges):
        adj[u].append((v, i))
        adj[v].append((u, i))
    disc = [-1] * n
    low = [0] * n
    bridges = []
    clock = 0

    def dfs(u, parent, via):
        nonlocal clock
        disc[u] = low[u] = clock
        clock += 1
        for v, i in adj[u]:
            if (i == via) if skip_by_id else (v == parent):
                continue
            if disc[v] == -1:
                dfs(v, u, i)
                low[u] = min(low[u], low[v])
                if low[v] > disc[u] or (not strict and low[v] == disc[u]):
                    bridges.append((u, v))
            else:
                low[u] = min(low[u], disc[v])

    for s in range(n):
        if disc[s] == -1:
            dfs(s, -1, -1)
    return bridges, disc, low


def two_edge_components(n, edges, bridges):
    cut = {frozenset(b) for b in bridges}
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    for u, v in edges:
        if frozenset((u, v)) not in cut:
            parent[find(u)] = find(v)
    groups = {}
    for v in range(n):
        groups.setdefault(find(v), []).append(v)
    return sorted(groups.values())


edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3), (5, 6), (6, 7), (6, 7)]
n = 8
bridges, disc, low = find_bridges(n, edges)
print("disc:", disc)
print("low: ", low)
print("bridges:", bridges)
print("2-edge-connected components:", two_edge_components(n, edges, bridges))

print("skip parent by vertex, not edge:", find_bridges(n, edges, skip_by_id=False)[0])
print("test low[v] >= disc[u]:", find_bridges(n, edges, strict=False)[0])

print("a path 0-1-2:", find_bridges(3, [(0, 1), (1, 2)])[0])
print("a cycle 0-1-2-0:", find_bridges(3, [(0, 1), (1, 2), (2, 0)])[0])
#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using Edge = pair<int, int>;

struct Bridges {
    vector<vector<pair<int, int>>> adj;
    vector<int> disc, low;
    vector<Edge> bridges;
    bool skipById, strict;
    int clock = 0;

    Bridges(int n, const vector<Edge>& edges, bool byId = true, bool strictTest = true)
        : adj(n), disc(n, -1), low(n, 0), skipById(byId), strict(strictTest) {
        for (int i = 0; i < (int)edges.size(); i++) {
            adj[edges[i].first].push_back({edges[i].second, i});
            adj[edges[i].second].push_back({edges[i].first, i});
        }
        for (int s = 0; s < n; s++)
            if (disc[s] == -1) dfs(s, -1, -1);
    }

    void dfs(int u, int parent, int via) {
        disc[u] = low[u] = clock++;
        for (auto [v, i] : adj[u]) {
            if (skipById ? i == via : v == parent) continue;
            if (disc[v] == -1) {
                dfs(v, u, i);
                low[u] = min(low[u], low[v]);
                if (low[v] > disc[u] || (!strict && low[v] == disc[u])) bridges.push_back({u, v});
            } else {
                low[u] = min(low[u], disc[v]);
            }
        }
    }
};

vector<vector<int>> twoEdgeComponents(int n, const vector<Edge>& edges, const vector<Edge>& bridges) {
    vector<int> parent(n);
    iota(parent.begin(), parent.end(), 0);
    auto find = [&](int x) {
        while (parent[x] != x) x = parent[x] = parent[parent[x]];
        return x;
    };
    auto isBridge = [&](Edge e) {
        for (auto [a, b] : bridges)
            if ((a == e.first && b == e.second) || (a == e.second && b == e.first)) return true;
        return false;
    };
    for (auto e : edges)
        if (!isBridge(e)) parent[find(e.first)] = find(e.second);
    map<int, vector<int>> groups;
    for (int v = 0; v < n; v++) groups[find(v)].push_back(v);
    vector<vector<int>> out;
    for (auto& [root, g] : groups) out.push_back(g);
    sort(out.begin(), out.end());
    return out;
}

string show(const vector<int>& v) {
    string s = "[";
    for (size_t i = 0; i < v.size(); i++) s += (i ? ", " : "") + to_string(v[i]);
    return s + "]";
}

string show(const vector<Edge>& es) {
    string s = "[";
    for (size_t i = 0; i < es.size(); i++) s += (i ? ", (" : "(") + to_string(es[i].first) + ", " + to_string(es[i].second) + ")";
    return s + "]";
}

int main() {
    vector<Edge> edges = {{0, 1}, {1, 2}, {2, 0}, {1, 3}, {3, 4}, {4, 5}, {5, 3}, {5, 6}, {6, 7}, {6, 7}};
    int n = 8;
    Bridges b(n, edges);
    cout << "disc: " << show(b.disc) << "\n";
    cout << "low:  " << show(b.low) << "\n";
    cout << "bridges: " << show(b.bridges) << "\n";
    cout << "2-edge-connected components: [";
    auto comps = twoEdgeComponents(n, edges, b.bridges);
    for (size_t i = 0; i < comps.size(); i++) cout << (i ? ", " : "") << show(comps[i]);
    cout << "]\n";

    cout << "skip parent by vertex, not edge: " << show(Bridges(n, edges, false).bridges) << "\n";
    cout << "test low[v] >= disc[u]: " << show(Bridges(n, edges, true, false).bridges) << "\n";

    cout << "a path 0-1-2: " << show(Bridges(3, {{0, 1}, {1, 2}}).bridges) << "\n";
    cout << "a cycle 0-1-2-0: " << show(Bridges(3, {{0, 1}, {1, 2}, {2, 0}}).bridges) << "\n";
}
import java.util.*;

public class Main {
    static List<List<int[]>> adj;
    static int[] disc, low;
    static List<String> bridges;
    static boolean skipById, strict;
    static int clock;

    static List<String> findBridges(int n, int[][] edges, boolean byId, boolean strictTest) {
        adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int i = 0; i < edges.length; i++) {
            adj.get(edges[i][0]).add(new int[]{edges[i][1], i});
            adj.get(edges[i][1]).add(new int[]{edges[i][0], i});
        }
        disc = new int[n];
        low = new int[n];
        Arrays.fill(disc, -1);
        bridges = new ArrayList<>();
        skipById = byId;
        strict = strictTest;
        clock = 0;
        for (int s = 0; s < n; s++)
            if (disc[s] == -1) dfs(s, -1, -1);
        return bridges;
    }

    static void dfs(int u, int parent, int via) {
        disc[u] = low[u] = clock++;
        for (int[] e : adj.get(u)) {
            int v = e[0], i = e[1];
            if (skipById ? i == via : v == parent) continue;
            if (disc[v] == -1) {
                dfs(v, u, i);
                low[u] = Math.min(low[u], low[v]);
                if (low[v] > disc[u] || (!strict && low[v] == disc[u])) bridges.add("(" + u + ", " + v + ")");
            } else {
                low[u] = Math.min(low[u], disc[v]);
            }
        }
    }

    static int find(int[] parent, int x) {
        while (parent[x] != x) x = parent[x] = parent[parent[x]];
        return x;
    }

    static List<List<Integer>> twoEdgeComponents(int n, int[][] edges, List<String> cut) {
        int[] parent = new int[n];
        for (int i = 0; i < n; i++) parent[i] = i;
        for (int[] e : edges) {
            boolean bridge = cut.contains("(" + e[0] + ", " + e[1] + ")") || cut.contains("(" + e[1] + ", " + e[0] + ")");
            if (!bridge) parent[find(parent, e[0])] = find(parent, e[1]);
        }
        TreeMap<Integer, List<Integer>> groups = new TreeMap<>();
        for (int v = 0; v < n; v++) groups.computeIfAbsent(find(parent, v), k -> new ArrayList<>()).add(v);
        List<List<Integer>> out = new ArrayList<>(groups.values());
        out.sort(Comparator.comparing(g -> g.get(0)));
        return out;
    }

    public static void main(String[] args) {
        int[][] edges = {{0, 1}, {1, 2}, {2, 0}, {1, 3}, {3, 4}, {4, 5}, {5, 3}, {5, 6}, {6, 7}, {6, 7}};
        int n = 8;
        List<String> found = findBridges(n, edges, true, true);
        System.out.println("disc: " + Arrays.toString(disc));
        System.out.println("low:  " + Arrays.toString(low));
        System.out.println("bridges: " + found);
        System.out.println("2-edge-connected components: " + twoEdgeComponents(n, edges, found));

        System.out.println("skip parent by vertex, not edge: " + findBridges(n, edges, false, true));
        System.out.println("test low[v] >= disc[u]: " + findBridges(n, edges, true, false));

        System.out.println("a path 0-1-2: " + findBridges(3, new int[][]{{0, 1}, {1, 2}}, true, true));
        System.out.println("a cycle 0-1-2-0: " + findBridges(3, new int[][]{{0, 1}, {1, 2}, {2, 0}}, true, true));
    }
}
Watch it run

Step through it

Running on 0–1, 1–2, 2–0, 1–3, 3–4, 4–5, 5–3, 5–6, 6–7, 6–7

undirected DFS · disc, low, and low[v] > disc[u] on each tree edge01234567TEST ON TREE EDGE u–vlow[v] > disc[u] ?BRIDGES FOUNDnone yetedges 0–1 1–2 2–0 1–3 3–4 4–5 5–3 5–6 6–7 6–7blue: tree edge · green dashed: edge back to an ancestor
Step 1

Eight vertices, ten edges

Two triangles joined by the edge 1–3, then an edge 5–6 to a pair of vertices that share two parallel edges. Which edges, if cut, split the graph? One depth-first search will answer, without deleting anything.

Output
1 / 13
4

Worked Example

Eight vertices, ten edges: a triangle 0–1–2, an edge 1–3, a triangle 3–4–5, an edge 5–6, and two parallel edges between 6 and 7. The search from 0 goes 0, 1, 2, then back to 1 and on to 3, 4, 5, 6, 7, so disc is simply 0 to 7.

The non-tree edge 2–0 gives low[2] = 0, and that is passed up to 1. The non-tree edge 5–3 gives low[5] = 3, passed up to 4 and 3. The second edge between 6 and 7 gives low[7] = 6. Now test the tree edges: 1–3 has low[3] = 3 > disc[1] = 1, a bridge. 5–6 has low[6] = 6 > disc[5] = 5, a bridge. Every other tree edge fails the test, because some non-tree edge below it reaches its upper end or higher.

  • low = 0, 0, 0, 3, 3, 3, 6, 6 for vertices 0 to 7
  • Bridges: 5–6 and 1–3 (reported in that order, as the search unwinds)
  • 6–7 is not a bridge: the parallel edge is a second route
5

Parallel Edges: Skip the Edge, Not the Vertex

Many versions skip the parent by vertex: 'ignore any edge back to the vertex I came from'. On a simple graph that is fine. With two edges between 6 and 7 it throws away the second edge too, low[7] stays 7, and 6–7 is reported as a bridge although cutting one of the two edges leaves the other.

Give every edge an id and skip only the id you arrived by. Road and network data often has duplicate links, which is exactly when the vertex version gives wrong answers.

6

Strictly Greater, Not Greater or Equal

The test for a cut vertex in articulation points is low[v] ≥ disc[u]: if v's subtree can climb only as far as u itself, removing u cuts it off. For an edge that is not enough. If v's subtree reaches u by another edge, there is a cycle through u–v and the edge is safe.

Using ≥ for edges on the example reports 6–7, 5–6, 3–4, 1–3 and 0–1. The extra three are all on cycles: 3–4 is in the triangle 3–4–5, 0–1 in the triangle 0–1–2, and 6–7 has its twin.

7

2-Edge-Connected Components and the Bridge Tree

Delete every bridge and the pieces that remain are the 2-edge-connected components: inside each one, any two vertices stay connected even if one edge fails. In the example they are {0, 1, 2}, {3, 4, 5} and {6, 7}.

Shrink each piece to a single node and keep the bridges as edges. The result is always a tree, because a cycle among the pieces would put those bridges on a cycle. This bridge tree answers reliability questions directly. For example, the fewest new links that remove every bridge is ⌈leaves / 2⌉, by joining leaves of the tree in pairs.

8

Cost, Recursion and Uses

The search visits each vertex once and each edge twice (once from each end), so it runs in O(V + E) time with O(V) extra memory for disc, low and the recursion. Deep paths overflow the call stack in the recursive form; an explicit stack of (vertex, arriving edge id, next edge index) frames removes the limit.

Bridges are single points of failure: a road whose closure strands a district, a cable whose loss splits a data centre. The interview version is critical connections in a network: given servers and links, list every link whose failure disconnects some servers, which is exactly the list of bridges.