Building a Hamiltonian path solver
| Built with | Unity 6 (6000.4.3f1) |
|---|
Introduction
Eulerian Aurora is a game my team is building. For its map editor I wrote a solver that checks whether the current map can be solved. The rules are simple. You have to visit every cell at least once, and you can’t go back over a path you’ve already taken (unless a gimmick lets you). So it’s a 3D Hamiltonian path puzzle. There are also six gimmicks, which I’ll go through one at a time later.
Finding a Hamiltonian path on a general grid is NP-complete. Put simply, if someone hands you a path, it’s easy to check that it’s correct, but an efficient algorithm that finds that path from scratch is very hard to come by. Our game made it harder still, because some gimmicks break the usual Hamiltonian rules and others multiply the number of cases. My first version was a brute-force DFS, and it blew up in my face.
Recently I came across research on finding Hamiltonian paths efficiently, applied it, and it worked (meaning it was fast enough for the number of states in our game, not that it’s a general solution).
How it differs from DFS
The problem with DFS was that there were too many cases, so it took a very long time.
The current solver instead builds a graph that fits the situation, then cuts the search down hard with pruning, search priority, skipping states it has already computed (similar to memoization), and a color check. The answer is still hard to find, but wrong paths can be cut off earlier than you’d expect.
Optimization
Pruning 1: connectivity check
If the state graph has a vertex that can’t be reached, there’s no answer. A BFS from the current cell can’t reach disconnected regions, so the state can be thrown out early.
Pruning 2: endpoint check
If, not counting the current cell, two or more cells have only one connection, the branch is dropped.
Both checks run in the same single BFS in CannotFinish(). While visiting, it counts each cell’s connections (degree), and the moment a second cell with only one connection shows up, it returns failure. If the BFS finishes with fewer unpainted cells reached than there are cells left, some region is cut off.
// PuzzleSolver.cs, Search.CannotFinish()
int reached = 1, leaves = 0, unpaintedReached = 0;
_queue[0] = state.Position;
_reached[state.Position] = ++_visit;
for (int i = 0; i < reached; i++)
{
int cell = _queue[i];
if (!TileHelper.IsPainted(tiles[cell]))
unpaintedReached++;
int degree = 0;
// ...
for (int d = 0; d < Directions.Length; d++)
if (Visit(_neighbors[cell, d]))
degree++;
// ...
if (!portal && !laser && cell != state.Position && degree == 1 && ++leaves > 1)
return true;
if (portal && IsPortal(tiles[cell]))
Visit(state.Portals[cell]);
}
return unpaintedReached < state.Unpainted;
If the map has a gimmick that breaks the endpoint check, that check is skipped.
Priority and no repeated search
A priority queue explores states with fewer cells left first. The idea is to reach the answer as early as possible.
Visited states are also stored, so if the current state is the same as one already seen, it isn’t searched again, even if it was reached by a different path. It’s the same intent as memoization in DP problems.
The priority queue is a SortedDictionary<int, Stack<Node>>. The key is the number of cells left.
// PuzzleSolver.cs, Search.Explore()
var pending = new SortedDictionary<int, Stack<Node>>();
var seen = new HashSet<(string, string, int, int, bool, int, MapGimmick)>();
// ...
while (pending.Count != 0)
{
// ...
var node = bucket.Value.Pop();
// ...
if (!trackGimmicks && CannotFinish(node.State))
continue;
children.Clear();
for (int d = 0; d < Directions.Length; d++)
{
var next = Advance(node.State, d, trackGimmicks: trackGimmicks);
if (next == null)
continue;
// ...
if (!solved && (seen.Count >= budget || !seen.Add(Key(next))))
continue;
int traceIndex = trace.Count;
trace.Add((node.TraceIndex, d));
if (solved)
return BuildSolution(trace, traceIndex, initial, explored);
children.Add(new Node(next, traceIndex, d));
}
// ...
}
Pre-check: color count (only without gimmicks)
When a map passes both the connectivity and endpoint checks but simply has a lot of cells, the search still gets big. In that case a color count can settle beforehand whether an answer can exist. Split the cells into two colors by whether the coordinate sum x + y + z is even or odd. This “color” has nothing to do with the paint state in the game rules. Say (1, 1, 1) is black and (1, 1, 2) is white. A Hamiltonian path steps on each cell once, so the two colors have to alternate.
| Total cells | For an answer to exist |
|---|---|
| Even | Both colors have the same number of cells. |
| Odd | The start color has one more cell than the other color. |
For example, with an odd number of cells the path always goes start color → other color → start color → … → start color. So with an even number of cells the search only runs when start color minus other color is 0, and with an odd number only when it’s 1.
This check runs once before the search.
// PuzzleSolver.cs, Search.HasValidStartColor()
int startColor = Color(state.Position);
int balance = 0;
foreach (int cell in _surfaceCells)
if (state.Tiles[cell] != (char)TileType.Empty)
balance += Color(cell) == startColor ? 1 : -1;
return balance is 0 or 1;
int Color(int cell)
{
var p = _positions[cell];
return (p.x + p.y + p.z) & 1;
}
With gimmicks
On maps with gimmicks, the conditions get much trickier depending on which gimmicks are present. The solver may adjust the graph’s connections, run certain checks on a looser graph than the real connections, or skip a check entirely.
| Gimmick | Rule it breaks |
|---|---|
| Portal | You only ever move to a neighboring cell |
| Ghost | You can’t enter a cell that’s already painted |
| Inverter | A painted cell stays painted |
| Laser | Only the cells the player walked over get painted |
| Dash | One direction input is one move |
| Layer rotation | Cell positions and adjacency are fixed |
Portal
You can arrive at an exit through its entrance even if the exit is already painted.
With portals, the endpoint check is skipped.
Ghost
While a ghost is active, or there are ghost tiles still left to trigger, the connectivity and endpoint checks are skipped during the search.
The one exception is the pre-search connectivity check on rotation maps without inverters, where paint state is ignored and every existing cell counts as connected to its neighbors. Ghosts can’t cross empty space either, so if even this wider graph has a disconnected region, the map has no answer.
Inverter
The number of cells left can go up partway through, and a region the player can’t reach can get painted by an inversion alone. So the connectivity and endpoint checks don’t hold.
While there’s an inverter that can still be triggered, the connectivity and endpoint checks are skipped during the search. Rotation maps with inverters are also left out of the pre-search connectivity check.
The default priority, which looks at states with fewer cells left first, doesn’t account for inverters properly. So on inverter maps where the default search hits its limit, the solver searches toward nearby inverters first. The priority is surface cell count + inputs so far + Manhattan distance to the nearest inverter.
Laser
While the player is holding a laser, or there are lasers left to pick up, the endpoint check is skipped, because a dead-end branch can be painted with the laser. A laser can’t reach another connected component across empty space, so it can still be included in the pre-search connectivity check on rotation maps without inverters.
Dash
The connectivity check doesn’t apply the dash’s forced direction and allows the normal neighbor connections as well, because when the dash direction is blocked you aren’t pushed that way and can move in whatever direction you want. If even this wider graph has unpainted cells that can’t be reached, the branch can safely be dropped.
Once a state passes the check, Advance runs the real dash direction and chained moves, so a fake answer never gets accepted.
Rotation
Layers in the same group rotate together. Besides the tile layout and player position, the dash directions and the portal links that change with rotation are updated too. Cells inside a group keep their adjacency to each other, while their contact with other groups and fixed layers changes.
On rotation maps without inverters, the search for cut-off regions includes the connections that could appear after a rotation.
Rotation maps whose starting tiles are only plain paths, lasers and dashes reuse the rotation connection graph.
Putting it into the solver
1. Initial state and pre-checks
PrepareSearch reads the map size, rotation settings, tile and portal data and so on, and builds the initial state. If the input data is invalid, it returns InvalidMap before searching.
Then the pre-check that fits the map type is applied. Plain maps with no rotation and no gimmicks get the grid color count, and rotation maps without inverters get the pre-search connectivity check. If this step shows the map is impossible, it stops before generating a huge number of states.
2. Take a candidate state and try the next inputs
Explore keeps the candidates it hasn’t explored yet and takes them out one by one. In a normal search it looks at states with fewer unpainted cells first. Within the same priority it uses a stack, so the most recently added state comes out first.
It applies pruning to the state it took out, then passes each of the six direction inputs to Advance. When it finds one valid answer, it moves on to reconstruction.
3. Not searching the same state twice
Key bundles the tile types and paint layout, player position, ghost count, whether a laser is held, cells left and so on into one key.
// PuzzleSolver.cs, Search.Key()
// Interior cells stay empty.
return (board, portals, state.Position, state.Ghost, state.Laser, state.Unpainted, state.UsedGimmicks);
4. Limits and retrying in a different order
The general solver’s default limit is currently 70,000 states (DefaultStateLimit). At a set point in the search (in the code, once it has seen 12,000 states, RetryAfter), it can switch the processing order of candidates with the same priority and try up to 12,000 more states.
Inverter maps where the default search hits the limit also get a separate inverter-first search of up to 12,000 states.
5. Reconstructing and replaying the answer
When an answer candidate is found, BuildSolution walks back through the direction inputs to rebuild the input sequence. Then Replay runs that sequence again from the initial map with the same Advance used during the search.
The replay confirms that each input is valid, and at the end makes sure that zero cells are left and every real tile is painted. It also records the gimmicks actually used and the position path.
// PuzzleSolver.cs, Search.BuildSolution() / Replay()
var inputs = new Stack<int>();
for (int i = traceIndex; i >= 0; i = trace[i].parent)
inputs.Push(trace[i].direction);
return Replay(initial, inputs, explored);
// end of Replay()
if (state.Unpainted != 0)
return new SolveResult(SolveStatus.Inconclusive, $"입력 종료 후 미도색 칸이 {state.Unpainted}개 남았습니다.", explored);
if (Array.Exists(state.Tiles, tile => tile != (char)TileType.Empty && !TileHelper.IsPainted(tile)))
return new SolveResult(SolveStatus.Inconclusive, "남은 칸 수와 타일의 색칠 상태가 일치하지 않습니다.", explored);
6. Results
| Result | Meaning |
|---|---|
Solved |
Found an answer that passed the replay check. |
Unsolvable |
The check showed the map is impossible. |
Inconclusive |
Couldn’t reach a conclusion, because it hit the limit or the replay didn’t match. It doesn’t mean there’s no answer. |
InvalidMap |
The input map or settings are invalid, so a normal search can’t start. |
Test results
Search size compared
| Map | Old DFS | DFS + both checks | Current solver |
|---|---|---|---|
| No Item - 3 | 5,595 | 102 | 104 |
| No Item - 4 | 408,370 | 136 | 145 |
| No Item - 5 | 2,977,739 | 277 | 5,012 |
| Map with cells on every surface | stopped at 10,000,000 | 488 | 499 |
You might wonder why the current solver searches more than DFS + both checks. DFS + both checks depends heavily on the order it tries directions in. The table shows its smallest search size, but when you actually run it, the search can grow to more than twice that depending on the direction order. So it’s unstable. The current solver applies a search priority, so it always gives the same result and is stable.
Single-map timing. Test machine: AMD Ryzen 7 6800HS, NVIDIA GeForce RTX 3050 Laptop GPU, 16 GB RAM
| Map ID | Map | Cells | States searched | Direction inputs | Median (ms) |
|---|---|---|---|---|---|
| 0 | No Item - 1 | 36 | 35 | 35 | 0.20 |
| 1 | No Item - 2 | 41 | 40 | 40 | 0.21 |
| 2 | No Item - 3 | 98 | 104 | 97 | 0.43 |
| 3 | No Item - 4 | 116 | 145 | 115 | 0.68 |
| 4 | No Item - 5 | 120 | 5,012 | 119 | 31.00 |
| 100 | Rotation | 25 | 37 | 27 | 3.86 |
| 101 | Portal & Ghost | 37 | 102 | 39 | 0.50 |
| 102 | Dash & Laser | 100 | 110 | 88 | 0.65 |
| 103 | Inverter | 141 | 142 | 96 | 0.55 |
| 200 | Aries | 72 | 77 | 71 | 0.70 |
| 201 | Taurus | 70 | 1,050 | 64 | 4.07 |
| 202 | Gemini 1 | 103 | 121 | 74 | 1.08 |
| 203 | Gemini 2 | 103 | 78 | 75 | 0.43 |
| 204 | Gemini 3 | 102 | 263 | 75 | 0.97 |
| 205 | Cancer | 73 | 5,367 | 67 | 20.56 |
| 206 | Leo | 118 | 70 | 70 | 0.42 |
| 207 | Virgo | 86 | 119 | 75 | 0.72 |
| 208 | Capricornus | 67 | 8,929 | 67 | 54.11 |
| 209 | Libra | 73 | 10,056 | 76 | 84.98 |
| 210 | Scorpio | 80 | 5,973 | 82 | 42.02 |
| 211 | Sagittarius | 47 | 57 | 8 | 1.59 |
| 212 | Aquarius | 58 | 76 | 62 | 0.68 |
| 213 | Pisces | 42 | 90 | 41 | 1.22 |