八皇后问题

	#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;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值