八皇后问题(C++)

#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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值