AlgoFrames

Implicit graphs: grids, states and puzzles

Many problems are graphs in disguise: grid cells, game states and puzzle positions. Each cell or state is a vertex and each move is an edge.

Before you start: Adjacency matrix, adjacency list, edge list.

The idea

This grid has no list of connections. Each cell is a node, and the four cells beside it are its neighbors.

The program finds a neighbor with arithmetic: add 1 or subtract 1 to the row or the column. Nothing is stored.

Intuition

Draw each cell as a dot and join side-by-side cells with a line. The 3 × 3 grid becomes a graph with 9 nodes and 12 edges.

States can be nodes too. Here a state is a number: solid arrows are the move +1, dashed arrows the move ×2.

The search creates a state only when it reaches it. The full graph can be huge or endless, and it is never built.

Complexity

Each cell checks at most four neighbors, so a grid of V cells takes about 4 × V checks. A table of all pairs would hold V × V entries.

The rule is four lines of code and uses no memory. That is why grids are never stored as edge lists.

Pitfalls

Test the row and column before reading the cell. Row -1 is off the grid, but Python reads the last row instead.

Neighbors link both ways. Without a seen mark, a search walks from a cell to its neighbor and straight back.

Variations

A knight is the same idea with a different rule. Each legal jump is an edge, so the knight on (0, 1) has 3 neighbors.

A sliding puzzle is a graph too: each arrangement in the table is a node, and one slide is an edge. Only 6 of the 12 states on this loop are shown.

Code

Pseudocode

neighbors(grid, r, c)
  result ← empty list
  for each (dr, dc) in up, right, down, left
    nr ← r + dr; nc ← c + dc
    if (nr, nc) is inside the grid and grid[nr][nc] is open
      add (nr, nc) to result
  return result

Python

def neighbors(grid, r, c):
    result = []
    for dr, dc in ((-1, 0), (0, 1), (1, 0), (0, -1)):
        nr, nc = r + dr, c + dc
        if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == 0:
            result.append((nr, nc))
    return result

JavaScript

function neighbors(grid, r, c) {
  const result = [];
  for (const [dr, dc] of [[-1, 0], [0, 1], [1, 0], [0, -1]]) {
    const nr = r + dr, nc = c + dc;
    if (nr >= 0 && nc >= 0 && nr < grid.length && nc < grid[0].length && grid[nr][nc] === 0) {
      result.push([nr, nc]);
    }
  }
  return result;
}

Practice problems (6)

Neighbors of a cell Warm-up

In this grid, the dark cells are walls. A neighbor is an open cell directly above, right, below or left of the marked cell. Click every neighbor of the marked cell.

Count islands preview Warm-up

In this map, dark cells are water and light cells are land. Land cells that touch side to side belong to one island. Cells that touch only at a corner do not.

Watch the scan, then say how many islands the map has.

Knight moves Standard

A knight stands on square (r, c) of an n × n board. In one jump it moves two squares in one direction and one square in the other.

Return every square it can reach in one jump, as [row, column] pairs, in any order.

Fewest operations Standard

A number starts at start. One operation adds 1 to it or doubles it. Return the fewest operations that turn start into target.

Every number is a state and each operation is an edge. Values above target never help, so skip them.

Fewest knight moves Standard

A knight starts on square (0, 0) of an n × n board. Return the fewest jumps it needs to land on square (r, c), or -1 if it cannot get there.

A jump moves two squares in one direction and one square in the other, and the knight must stay on the board.

Model a puzzle as a graph Challenge

A sliding puzzle has a 2 × 3 board with five numbered tiles and one blank. One move slides a tile next to the blank into the blank. You want the fewest moves to reach the solved board.

Which graph lets breadth-first search answer this?

Related topics

Next on the path: Breadth-first search