用C++解决“八皇后问题”

今天,我完成了我学习编程史上的一座里程碑:完成了经典的“八皇后问题”。本来我用的不是递归,无奈不用递归实现的没有回溯功能,所以只能改成递归。而且递归一开始还遇到了点麻烦,我们一开始是从最后一行开始的,结果发现这样很难递归,就改成了从第一行开始。这是最后调试能运行的程序。

#include <iostream>
int answer[8][8];
void process(int);
bool check(int, int);
void print_answer(void);
int answer_count = 0;
int main(void)
{
using std::cout;
using std::endl;
int i, j;
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
answer[i][j] = 0;
}
}
process(0);
cout << "total answer:" << answer_count << endl;
return 0;
}
void print_answer(void)
{
using std::cout;
using std::endl;
int i, j;
answer_count++;
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
cout << answer[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void process(int n)
{
int i;
if (8 == n)
{
print_answer();
return;
}
for(i = 0; i < 8; i++)
{
if(check(n, i))
{
continue;
}
answer[n][i] = 1;
process(n + 1);
answer[n][i] = 0;
}
return;
}
bool check(int n, int m)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < 8; j++)
{
if (answer[i][j] != 1)
{
continue;
}
if (j == m)
{
return true;
}
else if (n - i == j - m)
{
return true;
}
else if (i - n == j - m)
{
return true;
}
}
}
return false;
}

很不错吧!

1人评论了“用C++解决“八皇后问题””

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

返回顶部