#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;
}
本文介绍了一个使用回溯法生成拉丁方的C++程序实现。该程序通过递归填充矩阵来寻找所有可能的拉丁方解,并统计了总的解决方案数量。文章包含完整的源代码,展示了如何检查每一步是否符合拉丁方的要求。
1385

被折叠的 条评论
为什么被折叠?



