#include <iostream>
using namespace std;
class Queen
{
public:
Queen()
{
this->count = 0;
this->init();
this->EightQueen(0);
cout << "\t共有 " << this->count << " 种方法!" << endl;
cout << "\n\t----------------\n" << endl;
}
// 初始化棋盘
void init()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
this->chess[i][j] = 0;
}
}
}
// 判断落点是否安全
bool notDanger(int row, int column)
{
int i = 0, j = 0;
for (i = 0; i < 8; i++)
{
// 同行或同列存在皇后
if (this->chess[i][column] == 1 || this->chess[row][i] == 1) { return false; }
for (j = 0; j < 8; j++)
{
if (this->chess[i][j] == 0) { continue; }
// 斜线方向存在皇后
// ↗ and ↙ ↖ and ↘
else if ( i + j == row + column || i - j == row - column)
{
return false;
}
}
}
// 未找到皇后,该点安全
return true;
}
// 显示棋盘
void showChess()
{
cout << "\t第 " << ++this->count << " 种方法:\n" << endl;
for (int i = 0; i < 8; i++)
{
cout << "\t";
for (int j = 0; j < 8; j++)
{
cout << (this->chess[i][j] == 1 ? "■" : "□");
}
cout << endl;
}
cout << "\n\t----------------\n" << endl;
}
// 开始摆盘
void EightQueen(int row)
{
// 每一列
for (int i = 0; i < 8; i++)
{
// 当前行当前列是否可落点
if (this->notDanger(row, i))
{
this->chess[row][i] = 1; // 落点
// 已经是末行则显示棋盘
if (7 == row) { this->showChess(); }
// 不是末行则递归到下一行
else { this->EightQueen(row + 1); }
// 回溯将当前落子恢复,再找下一个落点
this->chess[row][i] = 0;
}
}
}
private:
int chess[8][8];
int count;
};
void checkQueen()
{
Queen q;
}
int main()
{
checkQueen();
}
八皇后问题(C++)
最新推荐文章于 2024-07-07 14:15:19 发布