Turning a Grid into a Graph

A grid search can treat each permitted cell as a vertex and each legal move as a directed or undirected edge.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Count a short path
  2. Describe obstacles as part of adjacency
  3. Define moves and obstacles before calculating distances
  4. Generate neighbors with the right boundary conditions

Count a short path

On a blank grid moving only horizontally or vertically, row zero column zero reaches row one column one in two moves. Allowing diagonals can reduce that to one. Grid indices identify each position in the representation.

Describe obstacles as part of adjacency

Removing a blocked cell removes paths through it. A search can generate legal neighboring cells from local rules rather than materializing every edge. Use breadth-first search for shortest moves under equal step cost.[1]

Define moves and obstacles before calculating distances

In a two-by-three grid, start at \((0,0)\) and target \((0,2)\). Block \((0,1)\) and use horizontal or vertical moves. The direct two-step path is gone, but a four-step path goes along the lower row. See unweighted shortest route length.

(0,0) → (1,0) → (1,1) → (1,2) → (0,2)
Intermediate cells all in bounds and open
Allowing diagonals can change the shortest path

Generate neighbors with the right boundary conditions

A move from the last column should not accidentally wrap to the next row when using flattened coordinates. Test both corners, a blocked start and a board with one open row. If diagonal movement requires clear neighboring corners, include those checks.

References

  1. Eric Lehman, F. Thomson Leighton and Albert R. Meyer, Mathematics for Computer Science ↩