9io.ai / Blog

Hamiltonian path puzzles and the maths of one-line grids

The maths of Hamiltonian path puzzles, from Hamilton’s 1857 icosian game to checkerboard parity and why some one-line grids have no solution.

Key takeaways

  • Every step on a grid changes colour, so a line through every cell has its ends’ colours fixed.
  • On an even board the ends differ in colour, and on an odd board both sit on the corners’ colour.
  • On a plain rectangle, the colour test plus three thin-board exceptions decides exactly when a line exists.
  • Once cells can be missing or walls added, deciding whether such a line exists is NP-complete.
  • Pathfold draws the solution first, then adds clues until a logic solver finishes without guessing.

A one-line path puzzle, where you draw a single line through every cell of a grid, is a Hamiltonian path puzzle: the line has to visit every cell exactly once. Two pieces of maths explain most of how these puzzles behave. The checkerboard argument fixes where the line can start and end, since every step changes colour. On a board with an even number of cells the two ends sit on different colours, and on an odd board both sit on the colour of the corners. And a 1982 paper by Alon Itai, Christos Papadimitriou and Jayme Szwarcfiter showed that on a plain rectangle, that colour test plus three exceptions on very thin boards decides exactly when a line can join two given cells. On grids with cells missing, the same question is NP-complete.

We make Pathfold here at 9io. It’s a daily number path puzzle for iPhone and iPad, free on the App Store, and it adds numbered checkpoints, which the line must meet in order, and walls it can’t cross. Every Pathfold puzzle has exactly one solution that you can reach by reasoning, and the maths here is why that takes some engineering.

This post covers Hamilton’s puzzle of 1857, the colour argument with a short program you can run, the 1982 result, why it makes unique, logic-only puzzles a design problem, and how Pathfold’s generator deals with that, from the game’s source. If you’d rather just solve the puzzles, our guide to solving number path puzzles and Pathfold’s guide page are the places to start.

What a Hamiltonian path puzzle asks

Treat each cell as a point, called a vertex, and join two vertices with an edge when their cells sit side by side with no wall between them. That turns the board into a grid graph. A path that visits every vertex exactly once is a Hamiltonian path, and a closed path that returns to its start is a Hamiltonian cycle.

On the board In the graph
A cell A vertex
Two cells side by side, no wall between An edge
A wall A missing edge
One line through every cell A Hamiltonian path
1 and the highest number The path’s two ends, fixed in advance
The numbers in between Vertices the path must meet in order
A closed loop through every cell A Hamiltonian cycle

Colour the cells like a chessboard and every edge joins a dark cell to a light one, which makes a grid graph bipartite, and almost everything below follows from that fact.

Hamilton’s icosian game of 1857

The puzzle is older than the name. At the British Association’s meeting in Dublin in 1857, William Rowan Hamilton presented his icosian calculus and a game he called the Icosian. He handed round a lithograph of the board, a flat projection of the regular dodecahedron with holes at its corners for the ivory pins the game was played with.1 The calculus was an algebra Hamilton had invented to study the dodecahedron’s symmetries, and the game asked for a closed route along the dodecahedron’s edges through each of its 20 corners exactly once.2

Hamilton sold the publishing rights to Jaques and Son, a London maker of toys and games, which put the game on sale in 1859. He received £25, and the game didn’t sell well. Thomas Kirkman was studying routes like these round polyhedra in England at about the same time, but it’s Hamilton’s name that the routes carry today.2

The checkerboard argument

A step up, down, left or right always lands on the other colour, so the cells of any line alternate dark, light, dark, light. On a board of n cells, that alone fixes the colours of a line through every cell.

  • If n is even, the line has n/2 cells of each colour, so its two ends sit on different colours.
  • If n is odd, the line has one more cell of the colour it starts on, so it must start and end on whichever colour has more cells. On a rectangle with an odd number of cells, that’s the colour of the four corners.

The argument works on any piece of the line too. A stretch between two cells of the same colour takes an even number of steps, so it fills an odd number of cells between them, and a stretch between different colours fills an even number. A region that one stretch has to fill on its own therefore needs the right mix of colours for that stretch’s two ends. Here is what the rule says on the board sizes Pathfold uses.

Board Cells Dark and light cells Where 1 and the highest number must sit
5 × 5 25 13 and 12 Both on the corners’ colour
6 × 6 36 18 and 18 On different colours
7 × 7 49 25 and 24 Both on the corners’ colour
8 × 8 64 32 and 32 On different colours
9 × 9 81 41 and 40 Both on the corners’ colour
10 × 10 100 50 and 50 On different colours

All 9,400 puzzles bundled with Pathfold 1.0 put their ends where the table says, as they have to. The argument only rules lines out. Whether a pair of cells that passes can always be joined is a different question.

A parity checker you can run

Brute force answers that question for small boards. This Python program, written for this post, applies the colour test to every pair of cells on six rectangles, then searches every line through all the cells to find which pairs can really be joined.

from itertools import combinations

def cells(rows, cols):
    return [(r, c) for r in range(rows) for c in range(cols)]

def colour_test(rows, cols, a, b):
    """The checkerboard argument: can a line through every cell run from a to b?"""
    dark = lambda cell: (cell[0] + cell[1]) % 2 == 0   # the top-left corner is dark
    if rows * cols % 2 == 0:
        return dark(a) != dark(b)       # even board: ends on different colours
    return dark(a) and dark(b)          # odd board: both ends on the corners' colour

def joinable_pairs(rows, cols):
    """Every pair of cells joined by at least one line through all the cells (brute force)."""
    found, n = set(), rows * cols
    def walk(path, seen):
        if len(path) == n:
            found.add(frozenset((path[0], path[-1])))
            return
        r, c = path[-1]
        for nxt in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
            if 0 <= nxt[0] < rows and 0 <= nxt[1] < cols and nxt not in seen:
                seen.add(nxt)
                walk(path + [nxt], seen)
                seen.remove(nxt)
    for start in cells(rows, cols):
        walk([start], {start})
    return found

print("board  pairs  pass the test  have a line  pass, no line")
for rows, cols in [(2, 4), (3, 3), (3, 4), (4, 4), (4, 5), (5, 5)]:
    pairs = [frozenset(p) for p in combinations(cells(rows, cols), 2)]
    passing = {p for p in pairs if colour_test(rows, cols, *p)}
    real = joinable_pairs(rows, cols)
    assert real <= passing   # no line ever breaks the colour test
    print(f"{rows}x{cols}  {len(pairs):5}  {len(passing):13}  {len(real):11}  {len(passing - real):13}")

Run with Python 3.9, it prints this in a few seconds.

board  pairs  pass the test  have a line  pass, no line
2x4     28             16           14              2
3x3     36             10           10              0
3x4     66             36           29              7
4x4    120             64           64              0
4x5    190            100          100              0
5x5    300             78           78              0

The assertion never fails: on these six boards, no line breaks the colour test. On a 4 × 4 board, 56 of the 120 pairs fail the test, opposite corners among them, and none of those can be joined. The reverse holds on the 3 × 3, 4 × 4, 4 × 5 and 5 × 5 boards, where every pair that passes has a line. The misses are all on thin boards. On the 2 × 4 strip, two pairs pass and still fail, the two pairs of cells facing each other across the middle. On the 3 × 4 board seven fail, including the middle cells of its two short sides.

What the 1982 paper proved about grid graphs

Those thin-board misses are exactly what Itai, Papadimitriou and Szwarcfiter described in “Hamilton Paths in Grid Graphs”, published in the SIAM Journal on Computing in November 1982.3 In their terms a grid graph is a finite set of points of the integer grid, with an edge between every two points one unit apart, and it’s rectangular when its points fill a rectangle. For a rectangular grid graph and two of its vertices, the paper gives “necessary and sufficient conditions” for a Hamiltonian path between them. A path exists exactly when the two vertices pass the colour test and the board isn’t one of three forbidden cases.

  1. The board is a single row, and an end isn’t one of its two end cells.
  2. The board is two cells wide, and the ends are two cells facing each other across the strip, other than at its short ends.
  3. The board is three cells wide and an even number of cells long, and the ends sit in one of a family of positions the paper spells out.

Checking those conditions takes time linear in the length of the numbers that describe the board and the two cells, and the proof builds the path itself in time proportional to the number of cells. We checked our reading of the theorem with a longer version of the program above, on every pair of cells in 16 small board shapes up to 5 × 5, 3 × 8 and 4 × 6, and it matched every one.

The paper’s other half is the hard part. For general grid graphs, where cells can be missing, deciding whether a Hamiltonian path exists is NP-complete, and so is deciding whether a Hamiltonian cycle exists. A corollary covers rectangles with some edges removed, which is what walls do, and for those the problem is NP-complete too. The proof works by building, from any planar bipartite graph with no vertex of degree above 3, a grid that has a Hamiltonian cycle exactly when that graph does. As the abstract points out, the same construction gives a simpler proof that the Euclidean travelling salesman problem is NP-complete.

Why some path puzzles have no solution

Put together, the maths gives a short list of reasons a board can’t be solved.

  • Colour. If the ends sit on the wrong colours, no line exists, however the walls lie. In a number path puzzle the same goes for any region that one stretch between consecutive numbers has to fill alone.
  • A cut. If taking away one end cell, or both end cells together, splits the rest of the board, there’s no line. The paper derives its first two forbidden cases from exactly that.
  • Dead ends. A cell with only one open side can only be an end, so a board with three such cells has no line, and neither does one where such a cell isn’t an end.
  • Order. Checkpoints add their own failures. A pocket of cells that no two consecutive numbers sit beside can’t be filled at all.

Past those, a board with walls or missing cells can fail for reasons no known quick test catches. That’s what NP-completeness means in practice. Nobody knows a method that settles every such board in time growing only polynomially with its size, and finding one would prove P equal to NP.

Why unique, logic-only puzzles are a design problem

A puzzle maker needs three things from every board, and each is harder to guarantee than the one before. The board needs a solution, and for a rectangle with walls that is already the NP-complete question. It needs exactly one, which means showing that every other line fails, so a solver has to search until the alternatives run out. And the one solution has to be reachable by reasoning a person can do, one step at a time, with no trial and error. That last part needs a model of how players reason, written as a solver that only uses techniques a person would use and gives up where a person would have to guess. Pathfold’s generator sidesteps the first problem by building the answer before the puzzle, and spends its effort on the other two.

How Pathfold’s generator makes a puzzle

This is what the generator in Pathfold 1.0 does for each puzzle, from the game’s source.

  1. Draw a random line through every cell. It starts with a serpentine, row by row, and then tries thousands of backbite moves, 20 for every cell times the board’s side. In a backbite, an end of the line bites a neighbouring cell of the line and the loop that closes is reversed, so the line stays one path through every cell. This line will be the solution.
  2. Put numbers along it. 1 goes on the first cell and the highest number on the last, and the rest are spread evenly along the line.
  3. Make it guess-free. The human-style solver, the same one that writes Pathfold’s hints, tries to solve the board without guessing. Where it gets stuck, the exact solver, a depth-first search that stops once it has found two solutions, looks for a second line from that point. If it finds one, the generator adds a wall on an edge the other line uses and the solution doesn’t, or a number that the other line would reach in a different stretch. If the line is unique but the step still needs a guess, a wall or a number goes in at or just after that step.
  4. Prune towards a difficulty band. Numbers and walls come out again, one at a time, while the board stays guess-free and its score stays under the top of the band set for that day or pack, until it reaches a target score inside the band. The score weighs each step by the technique it needed, 1 for a corridor, 4 for number order, 8 for a look-ahead and 16 for a deeper one.
  5. Try again if it misses. It draws fresh lines, up to 80 for each daily, 60 for each level and 30 for each endless puzzle, and keeps the first board that lands in its band, or the closest.

Every technique the human-style solver uses is a proof, so a board it finishes without guessing has no second line. That’s why step 3 settles uniqueness and the logic requirement together. The day’s recipe also caps the techniques. Monday’s dailies never need more than number-order reasoning, while Wednesday’s and those from Friday to Sunday may need the deeper look-ahead. The exact solver prunes its search with dead ends, two-way cells, pockets that need a stretch, a matching of pockets to stretches, and the checkerboard rule for the whole board and for pockets only one stretch can fill. A verify command reruns both solvers over all 9,400 bundled puzzles, 1,300 dailies, 600 levels and 7,500 endless boards, and checks each for exactly one solution and a guess-free solve.

A checklist before you search for a line

  1. Count the cells. With an even count, the two ends must be on different colours. With an odd count, both must be on the colour that has more cells.
  2. Look for cells with only one open side. Each must be an end, so with three or more there’s no line.
  3. Check whether removing an end cell, or both, splits the board.
  4. On a plain rectangle at least four cells wide each way, stop there: passing step 1 means a line exists.
  5. On a board with walls, holes or checkpoints, check each pocket’s colours against the stretch that has to fill it, then search, pruning with dead ends and pockets.

  1. D. R. Wilkins, Trinity College Dublin, “The Icosian Calculus” (Hamilton’s papers and the 1857 British Association report), https://www.maths.tcd.ie/pub/HistMath/People/Hamilton/Icosian/ ↩

  2. Wikipedia, “Icosian game”, https://en.wikipedia.org/wiki/Icosian_game ↩↩

  3. Alon Itai, Christos H. Papadimitriou and Jayme Luiz Szwarcfiter, “Hamilton Paths in Grid Graphs”, SIAM Journal on Computing 11(4), 676–686, November 1982, https://doi.org/10.1137/0211056 ↩

Frequently asked questions

What is a Hamiltonian path puzzle?

A puzzle that asks for one route through every cell or point exactly once, such as a single line through every square of a grid. In graph terms that route is a Hamiltonian path, named after William Rowan Hamilton, whose icosian game of 1857 asked for a closed route through the 20 corners of a dodecahedron.

Why do some path puzzles have no solution?

Most often because of colour. On a chessboard colouring every step changes colour, so on a board with an even number of cells the line’s two ends must sit on different colours, and on an odd board both must sit on the colour that has more cells. Thin boards, dead-end cells and cut-off regions rule out more.

How does checkerboard parity work in puzzles?

Colour the grid like a chessboard. A step up, down, left or right always lands on the other colour, so any path alternates colours. Counting the colours of the cells a path has to cover then fixes which colours its two ends can have.

Is finding a Hamiltonian path on a grid NP-complete?

For grids in general, yes. Itai, Papadimitriou and Szwarcfiter proved in 1982 that the problem is NP-complete for grid graphs, and for rectangles with some edges removed. For a full rectangle and two given end cells, their conditions decide it in linear time.

What was Hamilton’s icosian game?

A puzzle William Rowan Hamilton presented in Dublin in 1857: a flat drawing of a dodecahedron with holes at its 20 corners for pins, where the aim was a closed route along the edges through every corner once. The London firm Jaques and Son sold it from 1859.

How does Pathfold make sure each puzzle has one solution?

Its generator draws a random line through every cell first and places numbers along it. Wherever an exact solver finds a second solution, or a logic solver would have to guess, it adds a wall or a number, and it checks that every bundled puzzle has exactly one solution and a guess-free solve.

Work with us

Building something like this?

9io is a small team of senior engineers with a fractional CTO. We work by the hour, and plans start at $5,000. Send us a note about your product. The reply comes from the person who'd do the work.