| Target | Construction |
|---|---|
| Latin square | |
| orthogonal Latin squares, odd | , |
| magic square, odd | Siamese method: move up-right, drop down on collision |
| magic square, | write in order, complement () the cells on the diagonals of every block |
| magic square, | LUX method (Conway), from the odd square of size |
| Hamiltonian path on a grid | snake (boustrophedon) order |
| domino tiling of a board with an even number of cells and no holes | pair along rows; colour arguments decide holes |
| matrix with given row and column sums (non-negative integers) | north-west corner rule: fill greedily |
Magic squares
vector<vector<int>> magicSquare(int n) { // n odd (Siamese) or n % 4 == 0; values 1..n^2
vector<vector<int>> a(n, vector<int>(n));
if (n % 2 == 1) {
int r = 0, c = n / 2;
for (int v = 1; v <= n * n; v++) {
a[r][c] = v;
int nr = (r - 1 + n) % n, nc = (c + 1) % n;
if (a[nr][nc]) nr = (r + 1) % n, nc = c;
r = nr, c = nc;
}
} else { // doubly even: complement the cells on the 4x4 diagonals
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {
int v = i * n + j + 1;
bool diag = (i % 4 == j % 4) || ((i % 4) + (j % 4) == 3);
a[i][j] = diag ? n * n + 1 - v : v;
}
}
return a;
}Proof: both constructions are magic
Let and write the 0-indexed value as (), so the cell holds .
Odd (Siamese). Let . Within a run of consecutive values ( fixed) the walk moves by ; after the run it moves by , so run starts at and value sits at . This map cell has determinant , so it is a bijection of : no cell is filled twice, and the up-right cell is occupied exactly at the end of a run (it is the run’s first cell), which is when the code steps down. In a fixed row , each appears once with , and also takes every value once ( is invertible mod odd ); the same holds in a fixed column (). Hence every row and column sums to . Central symmetry: the cell of is the reflection of the cell of (using ), so opposite cells hold and . The anti-diagonal is the set (row + col ), which meets every once, so it sums to ; the main diagonal consists of the centre and opposite pairs, each summing to , so it sums to too.
. Let . A cell is marked iff ; marked cells get . Each row has exactly marked cells, and inside every block of 4 columns the marked offsets sum to , the same as the unmarked ones, so the row sum is . The pattern is symmetric in , so columns work the same way. Every diagonal cell is marked: the main diagonal holds , a permutation of the natural diagonal , and the anti-diagonal similarly. Both constructions were checked for all valid .
Related: Constructive Algorithms, Profile DP (counting tilings).