您的位置:首页 > 其它

N皇后问题算法

2009-03-26 12:42 246 查看
N皇后问题 8皇后问题 算法 c++

在一个8×8(n×n)国际象棋盘上,有8个皇后,每个皇后占一格;要求皇后间不会出现相互“攻击”的现象,即不能有两个皇后处在同一行、同一列或同一对角线上。

#include <iostream>
using namespace std;
int n;
int *result;
bool find(int);
bool put(int, int);
int main()
{
cout << "input n:" << endl;
cin >> n;
result = new int[n+1];
for (int i = 1; i <= n; ++i)
result[i] = 0;
if(find(1))
{
//输出结果
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
if (result[i] ==j)
cout << "■";
else
cout << "□";
cout << endl;
}
}
else
cout << "No solution!" << endl;
return 0;
}
bool find(int i)
{
for (int j = 1; j <= n; ++j)
{
if (put(i,j))
{
result[i] = j;
if (i == n)
return true;
else if (find(i + 1))
return true;
else
result[i] = 0;
}
}
return false;
}
//(i,j)点是否可以放子
bool put(int i, int j)
{
for (int k = 1; k < i; ++k)
if (j == result[k] || i + j == k + result[k] || i - j == k - result[k] )
return false;
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: