Graph Theory37 sections · 1633 units
Open in Course

LeetCode 1091 Shortest Path in Binary Matrix - Grid BFS

Adapting the Graph

A grid is a graph in disguise. Each cell (r,c)(r, c) is a node. Two cells are neighbors if they are adjacent: up, down, left, right, or diagonals (depending on the problem). You do not need an explicit adjacency list. When processing cell (r,c)(r, c), check all 88 surrounding cells.

Skip cells that are out of bounds or blocked. Add valid cells to the queue. This implicit graph representation is common in grid problems. BFS on a grid works the same as BFS on any graph, but the neighbors are calculated on the fly instead of stored in advance.