NeetCode 150, stage 11: Graphs

← Backtracking · All 150 problems · Advanced Graphs →

A graph problem is a search problem. You start at a node, and you visit each node that you can reach. This stage trains the three tools that do the visit: DFS, BFS and union-find. A grid is also a graph, because each cell is a node and its four neighbours are its edges.

Garden notes: the Go syntax for this stage.

Problems on this page

#ProblemLevelPatternTemplate
1200. Number of IslandsMediumGrid DFS (flood fill)A: Grid DFS (flood fill)
2133. Clone GraphMediumDFS with a clone mapC: Clone with a map
3695. Max Area of IslandMediumGrid DFS (flood fill)A: Grid DFS (flood fill)
4417. Pacific Atlantic Water FlowMediumDFS from the bordersA: Grid DFS (flood fill)
5130. Surrounded RegionsMediumDFS from the bordersA: Grid DFS (flood fill)
6994. Rotting OrangesMediumMulti-source BFS by levelB: BFS by level from many sources
7286. Walls and GatesMediumMulti-source BFS by levelB: BFS by level from many sources
8207. Course ScheduleMediumTopological sort (Kahn)D: Topological sort
9210. Course Schedule IIMediumTopological sort (Kahn)D: Topological sort
10684. Redundant ConnectionMediumUnion-find, cycle detectionE: Union-find
11323. Number of Connected Components in an Undirected GraphMediumUnion-find, count the groupsE: Union-find
12261. Graph Valid TreeMediumUnion-find, cycle detectionE: Union-find
13127. Word LadderHardBFS on an implicit graphF: BFS on an implicit graph

Templates to memorize

Template A: Grid DFS (flood fill)

Signal

The input is a grid, and the problem says island, region, area or “connected”. You must count the groups of cells, measure them or change them.

// TEMPLATE A: grid DFS (flood fill). It counts the groups of connected 1
// cells.
func countGroups(grid [][]int) int {
    rows, cols := len(grid), len(grid[0])
    // down, up, right, left
    dirs := [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
 
    var fill func(r, c int) // declare first, so the closure can call itself
    fill = func(r, c int) {
        // 1. BOUNDS: outside the grid
        if r < 0 || r >= rows || c < 0 || c >= cols {
            return
        }
        if grid[r][c] != 1 { // 2. CHECK: not land, or already filled
            return
        }
        // 3. MARK before the calls, or the fill never stops
        grid[r][c] = 0
        for _, d := range dirs { // 4. SPREAD to the four neighbours
            fill(r+d[0], c+d[1])
        }
    }
 
    count := 0
    for r := 0; r < rows; r++ {
        for c := 0; c < cols; c++ {
            // START: a 1 that no fill reached is a new group
            if grid[r][c] == 1 {
                count++
                fill(r, c)
            }
        }
    }
    return count
}

The moves are BOUNDS, CHECK, MARK, then SPREAD. Mark the cell before the recursive calls. If you mark the cell after the calls, two neighbours call each other without end. Some problems ask which cells can reach the border. For these problems, start the fill at the border cells. Then the cells that the fill did not mark are the surrounded cells.

Say it

“Each cell is a node with four neighbours. I flood-fill from every land cell I have not visited, and I mark cells as I go, so each cell is visited once: O(m times n).”

Template B: BFS by level from many sources

Signal

The problem asks for the minimum time or the shortest distance in a grid, and many cells start at the same moment. The words “each minute”, “nearest” and “spreads” are the signal.

// TEMPLATE B: BFS by level from many sources. The 2 cells spread to the 1
// cells.
// It returns the number of levels until the spread stops.
func levelsToSpread(grid [][]int) int {
    rows, cols := len(grid), len(grid[0])
    dirs := [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
    queue := [][2]int{} // a cell is a [2]int: row, column
    for r := 0; r < rows; r++ {
        for c := 0; c < cols; c++ {
            if grid[r][c] == 2 {
                // 1. SEED: all the sources go in first
                queue = append(queue, [2]int{r, c})
            }
        }
    }
    levels := 0
    for len(queue) > 0 {
        // 2. LEVEL: only the cells in the queue now
        for n := len(queue); n > 0; n-- {
            cell := queue[0]
            queue = queue[1:] // POP from the front
            for _, d := range dirs {
                r, c := cell[0]+d[0], cell[1]+d[1]
                if r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] != 1 {
                    continue
                }
                // 3. MARK when you push, not when you pop
                grid[r][c] = 2
                // 4. PUSH for the next level
                queue = append(queue, [2]int{r, c})
            }
        }
        if len(queue) > 0 {
            levels++ // 5. COUNT a level only if it reached new cells
        }
    }
    return levels
}

The moves are SEED, LEVEL, MARK, then PUSH. Put all the sources in the queue before the loop starts. Then one BFS gives each cell its distance to the nearest source. Mark a cell when you push it. If you mark a cell when you pop it, the same cell enters the queue many times.

Say it

“I put all the sources in the queue first and run one BFS, level by level. Each level is one minute, and each cell enters the queue once, so it’s O(m times n).”

Template C: Clone with a map

Signal

You must make a deep copy of a structure that has pointers, and the pointers can make a cycle.

// TEMPLATE C: copy a graph with a map from each old node to its copy.
type graphNode struct {
    val   int
    edges []*graphNode
}
 
func copyGraph(start *graphNode) *graphNode {
    // old node -> copy, also the visited set
    copies := make(map[*graphNode]*graphNode)
 
    var copyNode func(old *graphNode) *graphNode
    copyNode = func(old *graphNode) *graphNode {
        if old == nil {
            return nil
        }
        // 1. CHECK: this node already has a copy
        if c, ok := copies[old]; ok {
            return c
        }
        c := &graphNode{val: old.val}
        // 2. STORE before the calls, so a cycle finds the copy
        copies[old] = c
        // 3. LINK the copy of each neighbour
        for _, next := range old.edges {
            c.edges = append(c.edges, copyNode(next))
        }
        return c
    }
    return copyNode(start)
}

The moves are CHECK, STORE, then LINK. The map has two jobs. It is the visited set, and it gives you the copy of each old node. Store the copy in the map before you copy its neighbours. If you store the copy later, a cycle makes the recursion run without end.

Say it

“I keep a map from each original node to its clone. The map is also my visited set, so the DFS copies every node once: O(V + E).”

Template D: Topological sort

Signal

The problem says prerequisite, dependency, “before” or “order of tasks”. The edges have a direction, and you must find a valid order or find a cycle.

// TEMPLATE D: topological sort with Kahn's algorithm. An edge [a, b] means
// "a before b".
// It returns an order of all the n nodes, or nil if the graph has a cycle.
func topoOrder(n int, edges [][]int) []int {
    adj := make([][]int, n) // adj[a] = the nodes that wait for a
    // indegree[b] = the number of nodes that b waits for
    indegree := make([]int, n)
    for _, e := range edges { // 1. BUILD the lists and the counts
        adj[e[0]] = append(adj[e[0]], e[1])
        indegree[e[1]]++
    }
    queue := []int{}
    for v := 0; v < n; v++ {
        if indegree[v] == 0 { // 2. SEED: the nodes that wait for nothing
            queue = append(queue, v)
        }
    }
    order := make([]int, 0, n)
    for len(queue) > 0 {
        v := queue[0]
        queue = queue[1:]
        order = append(order, v) // 3. TAKE a node that is ready
        for _, w := range adj[v] {
            indegree[w]-- // 4. RELEASE: w waits for one node less
            if indegree[w] == 0 {
                queue = append(queue, w)
            }
        }
    }
    if len(order) < n { // 5. CYCLE CHECK: a node in a cycle never gets to 0
        return nil
    }
    return order
}

The moves are BUILD, SEED, TAKE, RELEASE, then CYCLE CHECK. This is Kahn’s algorithm. The indegree of a node is the number of nodes that it waits for. A node in a cycle never gets to indegree 0. So if the order has fewer than n nodes, the graph has a cycle. Read the direction of each edge with care: in the course problems, the pair [a, b] means that b comes first.

Say it

“I count the incoming edges of each node and start with the nodes that have none. Each node I take releases its neighbours. If I take fewer than n nodes, there is a cycle. It’s O(V + E).”

Template E: Union-find

Signal

The edges have no direction, and they come one at a time. The problem asks if two nodes are connected, how many groups exist, or which edge closes a cycle.

// TEMPLATE E: union-find. Each group of connected nodes has one root.
type unionFind struct {
    parent []int // parent[x] == x means that x is a root
    size   []int // size[root] = the number of nodes in the group
}
 
func newUnionFind(n int) *unionFind {
    u := &unionFind{parent: make([]int, n), size: make([]int, n)}
    for i := 0; i < n; i++ {
        u.parent[i] = i // each node starts as its own root
        u.size[i] = 1
    }
    return u
}
 
// find returns the root of the group of x.
func (u *unionFind) find(x int) int {
    if u.parent[x] != x {
        // PATH COMPRESSION: point x at the root
        u.parent[x] = u.find(u.parent[x])
    }
    return u.parent[x]
}
 
// union joins the groups of a and b. It returns false if they were one
// group already.
func (u *unionFind) union(a, b int) bool {
    ra, rb := u.find(a), u.find(b) // always work on the roots
    if ra == rb {
        return false // the edge a-b closes a cycle
    }
    if u.size[ra] < u.size[rb] {
        ra, rb = rb, ra // UNION BY SIZE: ra is the larger group
    }
    u.parent[rb] = ra // the smaller group goes below the larger group
    u.size[ra] += u.size[rb]
    return true
}

The moves are FIND with path compression, then UNION by size. The union method returns false when the two nodes are already in one group. That result tells you that the edge closes a cycle. Always join the roots, not the nodes. The line parent[a] = b is a frequent mistake, because it moves one node and not its group.

Say it

“Union-find keeps one root per group. With path compression and union by size, each operation is almost O(1), so n edges cost about O(n).”

Template F: BFS on an implicit graph

Signal

The problem asks for the minimum number of steps to change one state into another state. The input has no edges. A rule tells you which states are one step apart.

// TEMPLATE F: BFS on an implicit graph. A node is a state, and a function
// makes
// the neighbours of a state. It returns the number of steps to the goal, or
// -1.
func stepsToGoal(start, goal string, neighbours func(string) []string) int {
    seen := map[string]bool{start: true}
    queue := []string{start}
    for steps := 0; len(queue) > 0; steps++ {
        for n := len(queue); n > 0; n-- { // one level = one step
            state := queue[0]
            queue = queue[1:]
            // 1. GOAL: the first time that BFS sees it is the shortest
            if state == goal {
                return steps
            }
            // 2. GENERATE the neighbours now
            for _, next := range neighbours(state) {
                if !seen[next] {
                    seen[next] = true // 3. MARK when you push
                    queue = append(queue, next)
                }
            }
        }
    }
    return -1 // the queue is empty: no path
}

The moves are GOAL, GENERATE, then MARK. You do not build the graph. You make the neighbours of a state when you pop the state. For words, change one letter at a time and keep the results that are in the word set. This costs 26 tries for each letter, and that is cheaper than a comparison with each other word.

Say it

“The words are nodes, and two words that differ by one letter share an edge. I don’t build the edges; I generate the neighbours during a BFS. BFS finds the shortest chain.”

Mistakes in this stage

  • fill := func(r, c int) { ... } cannot call itself. Declare var fill func(r, c int) first, then assign the function.
  • grid[r][c] == 1 is always false on a [][]byte grid. The cells hold the characters '0' and '1'.
  • make([][]bool, rows) gives rows nil slices. Make each row in a loop before you write to it.
  • An index outside the grid is a panic in Go. Check the bounds before you read grid[r][c].

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

200. Number of Islands

LeetCode 200 · Medium

133. Clone Graph

LeetCode 133 · Medium

695. Max Area of Island

LeetCode 695 · Medium

417. Pacific Atlantic Water Flow

LeetCode 417 · Medium

130. Surrounded Regions

LeetCode 130 · Medium

994. Rotting Oranges

LeetCode 994 · Medium

286. Walls and Gates

LeetCode 286 (premium) · free on NeetCode · Medium

207. Course Schedule

LeetCode 207 · Medium

210. Course Schedule II

LeetCode 210 · Medium

684. Redundant Connection

LeetCode 684 · Medium

323. Number of Connected Components in an Undirected Graph

LeetCode 323 (premium) · free on NeetCode · Medium

261. Graph Valid Tree

LeetCode 261 (premium) · free on NeetCode · Medium

127. Word Ladder

LeetCode 127 · Hard


← Backtracking · All 150 problems · Advanced Graphs →