Matrix as Graph
Shortest paths and distances in a grid: BFS from one cell, BFS from many cells at once, counting levels as time, and the deque trick for steps that cost 0 or 1.
Overview
A grid is a graph you never have to build. Each cell is a node, and its neighbors are the cells next to it. The Island Traversal topic uses that view to count regions, where DFS and BFS both work. This topic covers the questions where only BFS gives the right answer: fewest steps to a target, the distance from every cell to the nearest special cell, and how long something takes to spread.
The cell is the node
The neighbors of the cell in row r and column c are computed from r and c, and any that fall off the grid are skipped. Ask which moves count: four directions (sharing an edge) is the default, and eight (sharing an edge or a corner) is used by Shortest Path in Binary Matrix.
Each move has its own bounds check.
- Up: (r - 1, c), valid when r > 0.
- Down: (r + 1, c), valid when r 0.
- Right: (r, c + 1), valid when c < cols - 1.
- Diagonals, for eight-way moves only: (r ± 1, c ± 1), valid when both coordinates are in range.
A grid with R rows and C columns has R × C nodes. With four-way moves it has R(C - 1) horizontal edges and C(R - 1) vertical ones, which is 2RC - R - C in total: 12 for a 3 × 3 grid, 31 for 4 × 5. A traversal touches each cell and each edge a constant number of times, so it is O(R × C).
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio