Here is a modified algorithm, with vastly improved performance, using most of the construction method suggested by Stoyan and Strehl.
The algorithm constructs all 1,072 Hamiltonian cycles on a 6 by 6 grid in about 100ms, and all 4,638,576 Hamiltonian cycles on an 8 by 8 grid in about 20 minutes.
Here, the algorithm runs out of steam, as a 10 by 10 grid has 467,260,456,608 cycles (Sloane A003763)
To construct N by N Hamiltonian cycles, the algorithm builds up "induced subgraphs" (see diagram at left) of an (N-1) by (N-1) square graph one cell at a time, starting with the top row and working across each row in turn.
The top row is constructed by observing that the corner cells have to be inside the Hamiltonian Cycle, and that no two outside cells can be adjacent.
From then on, cells are added by testing whether a cell can be inside or outside (or both or neither) according to the rule that no 2 by 2 block can be any of these patterns:
A 2 by 2 block $a,b,c,d$ will match one of the four patterns iff $a=d$ and $b=c$
Additional tests check that:
- no 2 adjacent cells on the perimeter can be outside
- the total number of inside and outside cells does not exceed $\frac{N^2-2}{2}$ and $\frac{(N-2)^2}{2}$ respectively
- After the completion of a row, all inside cells are connected to the row just completed.
Python implementation
Here is the Python code for the algorithm.
Hamiltonians(N) yields all the Hamiltonian cycles for an N by N grid.
Hamiltonians(N) yields all the Hamiltonian cycles for an N by N grid.