📄
字号:
//1。应用回溯法时,所要求的解必须能表示成一个n-元组(x1,x2,x3----------xn),其中 xi取自某个有
//穷集Si。
//
//在编写隐式约束条件NextPosAbideByRule()的时候多次发生错误,花了很长时间才调试正确
//2。编写该函数规则:一定对每一个元素xi设立一个访问标志位vi,初试都为false,如果正在访问xi,
//就把vi设置为true;一旦要发生回溯到处理xi-1,就把vi还原为false。
#include<vector>
#include<iostream>
#include<cstdlib> //这个头文件包含了一些数学常用公式见c++标准程序库p582
using namespace std;
vector<int> chessBoard(20,0); //棋盘,以下标记录为行,其对应值为皇后所在的列数,值域为[1,n]
//从一开始计数,每个数字初试化为1
vector<bool> visited(20,false);
bool NextPosAbideByRule( int currentRow, int n)
{
//如果返回的是false则要发生回溯
//对第currentRow行放置皇后
//判断列和对角线有没有重复
if(!visited.at(currentRow))
{
chessBoard.at(currentRow) = 1;
visited.at(currentRow) = true;
}
else
++chessBoard.at(currentRow);
while( chessBoard.at(currentRow) <= n){
bool overlap = false;
int row;
for( row = 1;row < currentRow; row++ )
{
if((chessBoard.at(row) == chessBoard.at(currentRow))
|| (abs(currentRow - row) == abs( chessBoard.at(currentRow) - chessBoard.at(row))))
{
overlap = true;
break;
}
}//for
if ( overlap == false) //如果符合条件
{
return true;
visited.at(currentRow) = true;
}
else
++chessBoard.at(currentRow);
}//while
visited.at(currentRow) = false;//归位
return false; //如果循环中跳出来
}
void OutPut( int n)
{
cout<<"--------------------------"<<endl;
int i;
for( i = 1; i <= n; ++i)
cout<<" the colum of row " <<i<<" is " << chessBoard.at(i)<<endl;
}
int Queen( int n)
{
//下标都是从1开始计数。
// n行n列的棋盘上放置n个皇后,使得每两个皇后之间都不在同一行同一列或同一斜线上
int answerNum = 0; //解的个数
int workIndex = 1; //工作下标
while( workIndex > 0 )
{
if( NextPosAbideByRule( workIndex,n ) )
{
if( workIndex == n) //一条路径找到
{
if(answerNum < 10)
{
OutPut(n); //输出
}
answerNum++;
}
else
workIndex ++;
}
else
workIndex --;
}//while
return answerNum;
}
int main()
{
while(1){
std::fill(chessBoard.begin(),chessBoard.end(),0);//重新赋值
std::fill(visited.begin(),visited.end(),false);
int line;
cout<< "please input the lines you want to create a chessBoard "<<endl;
cin >> line;
int answerNum = Queen(line);
cout<<"answer num:"<<answerNum<<endl;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -