#include <iostream>
using namespace std;
const int N = 4;
int count = 0;
int result_num = 0;
int a[N][N];
void latin(int, int);
void print();
void clear();
bool ok();
void main()
{
clear();
latin(0,0);
cout << “There are ” << result_num << ” results” << endl;
}
void latin(int x, int y)
{
if (count == N * N)
{
print();
++result_num;
}
else
{
for (int i = 1; i <= N; ++i)
{
a[x][y] = i;
++count;
if (ok())
{
int yy = (y + 1) % N;
int xx = x;
if (y == N – 1)
xx = x + 1;
latin(xx, yy);
}
–count;
}
a[x][y] = 0;
}
}
void print()
{
for (int i = 0; i != N; ++i)
{
for (int j = 0; j != N; ++ j)
{
cout << a[i][j] << ‘ ‘;
}
cout << endl;
}
cout << endl;
}
void clear()
{
for (int i = 0; i != N; ++i)
{
for (int j = 0; j != N; ++ j)
{
a[i][j] = 0;
}
}
count = 0;
}
bool ok()
{
for (int i = 0; i != N; ++i)
{
for (int j = 0; j != N; ++j)
{
if (a[i][j] == 0)
continue;
int row = i,col = j;
for (int k = 0; k != N; ++k)
{
if (k != j)
{
if (a[row][k] == a[i][j])
return false;
}
}
for (k = 0; k != N; ++k)
{
if (k != i)
{
if (a[k][col] == a[i][j])
return false;
}
}
}
}
return true;
}