Skip to lesson

Graphs model complex networks, dependencies, and spatial boards. We master BFS shortest paths, DFS component exploration, Kahn's topological sort, and Disjoint Set Union.

Graph modeling: adjacency lists and implicit grid graphs

Graph modeling turns raw input into a structure you can traverse.

Java
int n = 4;int[][] edges = {{0, 1}, {1, 2}, {2, 0}, {2, 3}};List<List<Integer>> adj = new ArrayList<>();for (int i = 0; i < n; i++) adj.add(new ArrayList<>());for (int[] e : edges) {              // undirected: add both directions    adj.get(e[0]).add(e[1]);    adj.get(e[1]).add(e[0]);}// grid graph: cell (r, c) links to its 4 neighboursint[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

In coding challenges, graphs rarely arrive as ready-made node objects; they are typically presented as raw edge lists int[][] edges or 2D spatial matrices char[][] grid, and unlike trees they can contain cycles, multiple connected components, and disconnected nodes.

For explicit graphs, we construct an adjacency list Map<Integer, List<Integer>> or List<List<Integer>> in O(V + E) time. For 2D grid graphs (like Number of Islands), the grid is an implicit graph where each cell (r, c) connects to its 4 orthogonal neighbors. We navigate neighbors using directional vectors int[][] dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}}. Because graphs contain cycles, any traversal without visited tracking will loop infinitely and throw a StackOverflowError. Always maintain a boolean[] visited array or modify grid cells in-place (e.g. marking visited land '1' as water '0') to ensure every vertex is visited at most once.

BFS versus DFS: level-by-level search versus path discovery

Choosing between Breadth-First Search (BFS) and Depth-First Search (DFS) is a critical decision.

Example 1 · BFS Shortest Path in Unweighted Graph

BfsShortestPathDemo.javaJava
import java.util.*;
public class BfsShortestPathDemo {    public static int shortestPath(int n, int[][] edges, int start, int end) {        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]);        }
        Queue<Integer> queue = new ArrayDeque<>();        boolean[] visited = new boolean[n];
        queue.offer(start);        visited[start] = true;        int distance = 0;
        while (!queue.isEmpty()) {            int size = queue.size();            for (int i = 0; i < size; i++) {                int curr = queue.poll();                if (curr == end) return distance;                for (int neighbor : adj.get(curr)) {                    if (!visited[neighbor]) {                        visited[neighbor] = true;                        queue.offer(neighbor);                    }                }            }            distance++;        }        return -1;    }
    public static void main(String[] args) {        int[][] edges = {{0, 1}, {1, 2}, {0, 3}, {3, 4}, {4, 2}};        System.out.println("Shortest path 0 to 2: " + shortestPath(5, edges, 0, 2));    }}
Output
Shortest path 0 to 2: 2

What this code does

  • Path 0 -> 1 -> 2 has length 2.
  • Path 0 -> 3 -> 4 -> 2 has length 3.
  • BFS guarantees the first arrival at node 2 is the shortest path.

BFS uses a FIFO queue (ArrayDeque) to explore nodes level-by-level in expanding ripples. Its superpower is finding the shortest path in unweighted graphs: the first time BFS reaches a target vertex, the path taken is guaranteed to have the minimum number of edges. BFS powers problems like Word Ladder and Rotting Oranges. DFS uses recursion or an explicit stack to dive as deep as possible down a path before backtracking. It is the optimal tool for exhaustive path searches, connected component counting, connected area flood fills, and cycle detection in directed graphs. Both BFS and DFS run in strictly O(V + E) time on adjacency lists.

Topological sorting: Kahn's algorithm and cycle detection

A Directed Acyclic Graph (DAG) represents tasks with prerequisite dependencies, such as Course Schedule or build systems. A topological sort arranges vertices in a linear sequence such that for every directed edge u -> v, task u appears before task v.

Example 2 · Kahn's Algorithm for Topological Sort and Cycle Detection

KahnsTopologicalSortDemo.javaJava
import java.util.*;
public class KahnsTopologicalSortDemo {    public static int[] findOrder(int numCourses, int[][] prerequisites) {        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());        int[] inDegree = new int[numCourses];
        for (int[] pre : prerequisites) {            adj.get(pre[1]).add(pre[0]); // pre[1] must be taken before pre[0]            inDegree[pre[0]]++;        }
        Queue<Integer> queue = new ArrayDeque<>();        for (int i = 0; i < numCourses; i++) {            if (inDegree[i] == 0) queue.offer(i);        }
        int[] order = new int[numCourses];        int idx = 0;
        while (!queue.isEmpty()) {            int curr = queue.poll();            order[idx++] = curr;            for (int neighbor : adj.get(curr)) {                if (--inDegree[neighbor] == 0) queue.offer(neighbor);            }        }
        return idx == numCourses ? order : new int[0];    }
    public static void main(String[] args) {        int[][] pre = {{1, 0}, {2, 0}, {3, 1}, {3, 2}};        int[] res = findOrder(4, pre);        System.out.println("Topological order: " + Arrays.toString(res));    }}
Output
Topological order: [0, 1, 2, 3]

What this code does

  • Course 0 has in-degree 0 and is scheduled first.
  • Courses 1 and 2 become ready after course 0.
  • Course 3 is scheduled last once all prerequisites finish.

Kahn's Algorithm implements topological sorting using vertex in-degrees (the number of incoming edges pointing to each vertex):

  1. Compute the in-degree of all V vertices in O(V + E) time.
  2. Add all vertices with in-degree 0 to a FIFO queue.
  3. While the queue is not empty, poll vertex u, add u to the topological order, and decrement the in-degree of all its neighbors v. If neighbor v's in-degree drops to 0, enqueue v. If the number of processed vertices equals V, the graph is a valid DAG and the order is valid. If fewer than V vertices are processed, a directed cycle exists among the remaining nodes, making dependency resolution impossible.

Disjoint Set Union (Union-Find): dynamic connectivity

Disjoint Set Union (DSU), also known as Union-Find, tracks partitioned elements into disjoint sets and answers connectivity queries in near constant time. It supports two core operations: find(x) returning the root representative of x, and union(x, y) merging the sets containing x and y. Naive implementations link parent pointers directly, which can degenerate into a linear chain of depth N, degrading find to O(N) time.

Two vital optimizations eliminate this degradation: path compression and union by rank. Path compression flattens the tree during find(x) by pointing every traversed node directly to the root: parent[x] = find(parent[x]). Union by rank attaches the shallower tree under the root of the deeper tree during union(x, y).

Together, path compression and union by rank reduce the amortized time per operation to O(alpha(N)), where alpha is the Inverse Ackermann function. For all practical values of N <= 10^80, alpha(N) <= 4, providing practically O(1) performance.

Example 3 · Union-Find with Path Compression and Rank

UnionFindCycleDemo.javaJava
public class UnionFindCycleDemo {    static class DSU {        int[] parent, rank;        DSU(int n) {            parent = new int[n];            rank = new int[n];            for (int i = 0; i < n; i++) parent[i] = i;        }        int find(int x) {            if (parent[x] != x) parent[x] = find(parent[x]); // Path compression            return parent[x];        }        boolean union(int x, int y) {            int rootX = find(x), rootY = find(y);            if (rootX == rootY) return false; // Cycle detected            if (rank[rootX] < rank[rootY]) parent[rootX] = rootY;            else if (rank[rootX] > rank[rootY]) parent[rootY] = rootX;            else { parent[rootY] = rootX; rank[rootX]++; }            return true;        }    }
    public static void main(String[] args) {        DSU dsu = new DSU(4);        int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {3, 0}};        for (int[] e : edges) {            boolean added = dsu.union(e[0], e[1]);            if (!added) {                System.out.println("Cycle detected on edge: [" + e[0] + ", " + e[1] + "]");            }        }    }}
Output
Cycle detected on edge: [3, 0]

What this code does

  • Edges (0, 1), (1, 2), and (2, 3) merge nodes into a single component.
  • Edge (3, 0) connects nodes already in the same component, detecting the cycle.
  • Runs in practically O(1) amortized time per operation.

Next step

Check your understanding

10 quick questions