N皇后描述: 任何一行一列 45度斜线上都只能有一个皇后
要求: 以四皇后为例打印出符合条件的所有结果
#include <iostream>
#include <cmath>
using namespace std;
const int N = 4; //number of the box
int row[N+1] = {0};
void print()
{
cout <<"\n=========print graph begin=================\n";
for(int i=1; i<=N; i++)
{
for (int j=1; j<=N; j++)
{
if(row[i]==j)
{
cout << "1\t";
}
else
{
cout << "0\t";
}
}
cout << endl;
}
cout <<"=========print graph end====================\n\n";
}
bool PositionOk(int pos, int totalNum)
{
for(int i=1; i<pos;i++)
{
if(row[i]==row[pos] || abs(row[pos]-row[i])==pos-i)
{
return false;
}
}
return true;
}
void rn_queens(int currentNum , int totalNum)
{
for(row[currentNum]=1; row[currentNum]<=totalNum; row[currentNum]++)
{
if(PositionOk(currentNum,totalNum))
{
if(currentNum == totalNum)
{
for(int i=1; i<=totalNum; i++)
{
cout << row[i] << "\t";
}
cout << endl;
print();
}
else
{
rn_queens(currentNum+1,totalNum);
}
}
}
}
void n_queens(int totalNum)
{
rn_queens(1,totalNum);
}
int main()
{
n_queens(N);
cout << "hello world" << endl;
return 0;
}
显示结果如下:
说明:45度斜线判断 | f(y) - f(X) | = | y-x |
总结:回溯算法的常用形式
假设某个回溯算法其解有形式
x[1] x[2] x[3]..x[n]
再假定x[i]的值实在集S里,于是回溯算法的一般形式如下
backtrack(n)
{
rbacktrack(1,n)
}
rbacktrack(k,n)
{
for each x[k] belongto S
if(bound(k))
{
if(k==n)
{
print result
}
else
{
rbacktrack(k+1,n)
}
}
}
其中回溯算法的一个关卡就在编写一个高效的界定函数bound
本文通过C++实现N皇后问题的解决方法,并以四皇后为例展示所有可能的摆放方案。文章详细介绍了如何确保皇后间不发生冲突的条件判断,以及采用回溯算法实现的完整代码。
1442

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



