#include <iostream>
#include <cmath>
using namespace std;
int num = 0;
bool endFlag = false;
bool rowState[8];
//每一列的行数,索引代表列
int rowOfCol[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
void printResult() {
num ++;
for (int i = 0; i < 8; i ++)
cout<<rowOfCol[i];
cout<<endl;
}
bool isCollided(int col, int row)
{
if (col == 0)
return false;
int j = 0;
for (; j < col; j ++) {
int deltaRow = abs(rowOfCol[j]-row);
int deltaCol = abs(j-col);
if (deltaCol == deltaRow) {
return true;
}
}
if (j == col)
return false;
}
// 设置第col列的行数
void setRowOfCol(int col)
{
if (rowOfCol[col] != -1)
rowState[rowOfCol[col]] = false;
int i = 1 + rowOfCol[col];
for (; i < 8; i ++) {
if (!rowState[i]&&!isCollided(col, i)) {
rowState[i] = true;
rowOfCol[col] = i;
break;
}
}
if (i == 8) { //表示该列所有行都不能放置旗子了,这个时候就要重新设置前一列的行数
if (col == 0) { //表示所有结果都枚举了,结束
endFlag = true;
cout<<"\nTotally "<<num<<" Solutions\n";
return;
}
if (!endFlag) {
rowOfCol[col] = -1;
setRowOfCol(col-1);
setRowOfCol(col);
}
} else {
if (col == 7) { //一种方案成功,继续下一种
printResult();
setRowOfCol(7);
}
}
}
void octQueen()
{
for (int i = 0; i < 8; i ++)
setRowOfCol(i);
}
int main(){
octQueen();
return 0;
}
八皇后问题
最新推荐文章于 2023-07-07 14:04:01 发布