A Latin Square is a square of size n × n containing numbers 1 to n inclusive. Each number occurs once in each row and column.
An example of a 3 × 3 Latin Square is:
$$ \left( \begin{array}{ccc} 1 & 2 & 3 \\ 3 & 1 & 2 \\ 2 & 3 & 1 \\ \end{array} \right) $$ Another is: $$ \left( \begin{array}{ccc} 3 & 1 & 2 \\ 2 & 3 & 1 \\ 1 & 2 & 3 \\ \end{array} \right) $$
My code can work when the order is less than 5
n=4;
Dimensions[ans=Permutations[Permutations[Range[n]],{n}]//
Select[AllTrue[Join[#,Transpose@#],DuplicateFreeQ]&]]//AbsoluteTiming
{0.947582, {576, 4, 4}}
When the order is 5, the memory is not enough, I want to know if there is a better way to get all 5×5 Latin squares?