AlgoTales · Roadmap

Bridges

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A bridge is a single link whose removal splits a network into two separate parts. Finding bridges shows the fragile connections that deserve a backup, and you can find all of them in one pass.

Practical use cases

  • Web app: Office network health map. An IT dashboard draws offices and cables. Links that are the only way between two parts of the company are marked red as bridges, so the team knows which single cable cut would isolate a branch.
  • Web app: Fragile links in a website. A site audit finds pages that are the only link between a section and the rest, such as one menu item leading to the whole help centre. If that link breaks, hundreds of pages become unreachable, so editors add a second route.
  • Web app: Delivery network resilience report. A logistics app shows which road between depots has no alternative. Planners use this to pick which road to keep open during repair work.
  • System: Power grids and graph clean-up. Engineers check grids for single lines that could black out a region, and data tools use bridges to split a big network into natural clusters. The common idea is that removing one link must disconnect something, and a single walk can find all such links without testing them one by one.

The story: The Bridge That Cut the Town in Two

Grandpa Bhaskar's town sits on both banks of a river. During the floods the municipality asked a scary question: "Which single road, if it is closed, will cut the town in two?" These important roads are called bridges.

Mira's first idea was to close each road one by one and check if everybody could still reach everybody. With thousands of roads that took forever: close a road, run a search, open it, next road.

Her teacher showed a faster way. Walk through the town once with a DFS, giving each junction a number as you arrive. For each junction also note the oldest numbered junction you can reach by going down the tree and then using at most one back road. Now look at a road from junction U down to junction V. If the oldest place V's side can climb back to is still below U, nothing connects V's side to the rest except this road. If it can climb to U or higher, there is a back door.

So the rule is delightfully short: road U–V is a bridge if low(V) > disc(U). One walk, no repeated searches. These are also called cut edges.

How to spot this problem, and where you need it

You want to know which single link, if it failed, would disconnect part of your network, so you can protect or duplicate it.

Signs you need it

  • Words like "critical connection", "single point of failure", "if this link breaks, is anything cut off?" appear.
  • A report must list the weakest links, not just count groups.
  • Removing one edge and re-running a connectivity check works but takes forever when you try it for each edge.

Where to use it in a project

  • Infrastructure and uptime dashboards that highlight cables, links or routes with no backup.
  • Site structure audits, to find single links holding up whole sections.

The solution

Do one DFS and give every node a discovery number and a low number (the earliest node reachable from its subtree using at most one back-link). For a link from parent u to child v, if low of v is greater than the discovery number of u, then nothing in v's subtree can get above u without this link, so it is a bridge. One walk finds all of them.

Payoff: Before: removing each of 5,000 links and rechecking connectivity, minutes of work. After: one pass lists all bridges in milliseconds.

Explain it like I am 8

Picture two playgrounds joined by one little rope bridge. If the rope bridge breaks, the kids cannot visit each other. A bridge in a graph is that one rope: the only connection between two parts.

How it works, step by step

  1. Run a DFS and give each node a discovery number in order of arrival.
  2. Give every node a low number: the smallest discovery number reachable through its subtree plus one back road.
  3. For a tree road U → V, after returning from V, update low[U] = min(low[U], low[V]).
  4. If low[V] > disc[U], nobody below V can reach U or above except through this road: it is a bridge.
  5. Skip the road you came along (the parent road) when computing low, or every road would look like a back door.

The code in four languages

PHP

<?php
// Find all bridges with one DFS (discovery and low numbers)
function findBridges(int $n, array $edges): array {
    $adj = array_fill(0, $n, []);
    foreach ($edges as $id => [$a, $b]) {
        $adj[$a][] = [$b, $id];
        $adj[$b][] = [$a, $id];
    }
    $disc = array_fill(0, $n, -1);
    $low = array_fill(0, $n, 0);
    $bridges = [];
    $time = 0;

    $visit = function (int $u, int $parentEdge) use (&$visit, &$disc, &$low, &$bridges, &$time, $adj): void {
        $disc[$u] = $low[$u] = $time++;
        foreach ($adj[$u] as [$v, $id]) {
            if ($id === $parentEdge) continue;          // do not walk back the way we came
            if ($disc[$v] >= 0) {
                $low[$u] = min($low[$u], $disc[$v]);    // a back door to an older node
            } else {
                $visit($v, $id);
                $low[$u] = min($low[$u], $low[$v]);
                if ($low[$v] > $disc[$u]) {             // nothing below v reaches u or higher
                    $bridges[] = $u . '-' . $v;
                }
            }
        }
    };
    for ($i = 0; $i < $n; $i++) if ($disc[$i] < 0) $visit($i, -1);
    return $bridges;
}

// towns A..G = 0..6
$roads = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,5],[5,3],[4,6]];
echo 'Bridges: ' . implode(', ', findBridges(7, $roads)) . PHP_EOL;

JavaScript

// Find all bridges with one DFS (discovery and low numbers)
function findBridges(n, edges) {
  const adj = Array.from({ length: n }, () => []);
  edges.forEach(([a, b], id) => {
    adj[a].push([b, id]);
    adj[b].push([a, id]);
  });
  const disc = new Array(n).fill(-1);
  const low = new Array(n).fill(0);
  const bridges = [];
  let time = 0;

  function visit(u, parentEdge) {
    disc[u] = low[u] = time++;
    for (const [v, id] of adj[u]) {
      if (id === parentEdge) continue;            // do not walk back the way we came
      if (disc[v] >= 0) {
        low[u] = Math.min(low[u], disc[v]);       // a back door to an older node
      } else {
        visit(v, id);
        low[u] = Math.min(low[u], low[v]);
        if (low[v] > disc[u]) {                   // nothing below v reaches u or higher
          bridges.push(u + '-' + v);
        }
      }
    }
  }
  for (let i = 0; i < n; i++) if (disc[i] < 0) visit(i, -1);
  return bridges;
}

// towns A..G = 0..6
const roads = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,5],[5,3],[4,6]];
console.log('Bridges: ' + findBridges(7, roads).join(', '));

Java

import java.util.*;

public class Main {
    static List<List<int[]>> adj;           // each entry: {neighbour, edge id}
    static int[] disc, low;
    static List<String> bridges = new ArrayList<>();
    static int time = 0;

    static void visit(int u, int parentEdge) {
        disc[u] = low[u] = time++;
        for (int[] road : adj.get(u)) {
            int v = road[0], id = road[1];
            if (id == parentEdge) continue;             // do not walk back the way we came
            if (disc[v] >= 0) {
                low[u] = Math.min(low[u], disc[v]);     // a back door to an older node
            } else {
                visit(v, id);
                low[u] = Math.min(low[u], low[v]);
                if (low[v] > disc[u]) {                 // nothing below v reaches u or higher
                    bridges.add(u + "-" + v);
                }
            }
        }
    }

    // Find all bridges with one DFS (discovery and low numbers)
    static List<String> findBridges(int n, int[][] edges) {
        adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int id = 0; id < edges.length; id++) {
            adj.get(edges[id][0]).add(new int[]{edges[id][1], id});
            adj.get(edges[id][1]).add(new int[]{edges[id][0], id});
        }
        disc = new int[n];
        Arrays.fill(disc, -1);
        low = new int[n];
        for (int i = 0; i < n; i++) if (disc[i] < 0) visit(i, -1);
        return bridges;
    }

    public static void main(String[] args) {
        // towns A..G = 0..6
        int[][] roads = {{0, 1}, {1, 2}, {2, 0}, {2, 3}, {3, 4}, {4, 5}, {5, 3}, {4, 6}};
        System.out.println("Bridges: " + String.join(", ", findBridges(7, roads)));
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

type road struct{ to, id int }

// findBridges finds all bridges with one DFS (discovery and low numbers).
func findBridges(n int, edges [][2]int) []string {
	adj := make([][]road, n)
	for id, e := range edges {
		adj[e[0]] = append(adj[e[0]], road{e[1], id})
		adj[e[1]] = append(adj[e[1]], road{e[0], id})
	}
	disc := make([]int, n)
	for i := range disc {
		disc[i] = -1
	}
	low := make([]int, n)
	var bridges []string
	time := 0

	var visit func(u, parentEdge int)
	visit = func(u, parentEdge int) {
		disc[u], low[u] = time, time
		time++
		for _, r := range adj[u] {
			if r.id == parentEdge {
				continue // do not walk back the way we came
			}
			if disc[r.to] >= 0 {
				low[u] = min(low[u], disc[r.to]) // a back door to an older node
			} else {
				visit(r.to, r.id)
				low[u] = min(low[u], low[r.to])
				if low[r.to] > disc[u] { // nothing below v reaches u or higher
					bridges = append(bridges, fmt.Sprintf("%d-%d", u, r.to))
				}
			}
		}
	}
	for i := 0; i < n; i++ {
		if disc[i] < 0 {
			visit(i, -1)
		}
	}
	return bridges
}

func main() {
	// towns A..G = 0..6
	roads := [][2]int{{0, 1}, {1, 2}, {2, 0}, {2, 3}, {3, 4}, {4, 5}, {5, 3}, {4, 6}}
	fmt.Println("Bridges: " + strings.Join(findBridges(7, roads), ", "))
}

Time: O(V + E) · Extra space: O(V + E). One DFS over the whole graph, no matter how many roads you want to test.

Watch out for

  • Not skipping the parent road, so every tree road looks like it has a back door to its own parent.
  • Using >= instead of >. For bridges it is strictly greater; >= is the rule for articulation points (next lesson).
  • Using the plain "skip parent node" trick on graphs with parallel roads (two roads between the same pair). Skip by road id instead, as in the code.

Quick check

  1. Which condition makes tree road U–V a bridge?
    • disc[V] > low[U]
    • low[V] < disc[U]
    • low[V] > disc[U]
    • low[V] == 0
  2. A back road leads from a node to an older ancestor. Can that road be a bridge?
    • No, it makes a loop so there is a way around
    • Only if it is the last road
    • Yes, always
  3. How long does the DFS method take for the whole graph?
    • One DFS per road
    • O(V cubed)
    • One DFS: O(V + E)