Courses / DSA Patterns for Working Engineers / Chapter 35
Module 11 · Graph algorithms · Chapter 35 of 39
Grids as Graphs: Flood Fill, Islands and Spreading
Builds on Matrices: Traversals, Rotations and In-Place Marking, Graphs: Modelling, Breadth-First and Depth-First Search and Union-Find: Merging Groups and Finding Redundant Links. Next up: Weighted Shortest Paths: Dijkstra, Bellman-Ford and 0-1 BFS.
Part 1 · Introduction to grids as graphs
Cells and neighbours
City maps, floor plans, game boards and photographs are grids, and many questions about them are graph questions in disguise: which cells are connected, how far is one cell from another, which cells can a spreading fault reach. This lesson shows how to see a grid as a graph and then fills a region of it.
Take every cell as a node. Two cells are joined by an edge when they are neighbours. Usually that means the four cells above, below, left and right, called 4-connected. Some problems also allow the four diagonal cells, called 8-connected. The graph is never built. Like the puzzle graphs of the previous chapter it is implicit, and the neighbours of a cell come from a short table of steps.
export const DIRS4 = [[1, 0], [-1, 0], [0, 1], [0, -1]] export const DIRS8 = [...DIRS4, [1, 1], [1, -1], [-1, 1], [-1, -1]]
fill.ts: the step tables used in this chapter
A cell at row r and column c has the neighbour [r + dr, c + dc] for each step [dr, dc] in the table. Two details come up in every grid problem. The first is the border. A neighbour with a negative index, or an index equal to the row or column count, is outside the grid, and it must be skipped. In JavaScript, reading grid[-1] gives undefined and then grid[-1][0] throws, while grid[nr]?.[nc] gives undefined for any outside cell. The code in this chapter uses that form where a cell's value is compared, and explicit bounds checks where it is not enough.