八皇后问题。

#include<bits/stdc++.h>
using namespace std;
int  book[92][9], mark[9], cnt = 0; //book记录全部解,mark记录当前解;
bool range[9], line1[17], line2[17]; //分别记录列方向,45度,135度方向上被控制的情况
bool isok(int i,int j)
{
	return range[j] || line1[i + j] || line2[i - j + 9];
}
void tryToPut(int i) {
	if (i > 8) { //如果最后一个皇后被放置完毕,将当前解复制到全部解中
		for (int k = 1; k <=8; k++)
		{
			book[cnt][k] = mark[k];
			cout << book[cnt][k];
		}
		cnt++;
		cout << endl;
	}
	for (int j = 1; j <= 8; j++) {
		if (!isok(i,j)) { //如果与前面的不冲突,//则把当前皇后放置在当前位置
			mark[i] = j;
			range[j] = line1[i + j] = line2[i - j + 9] = 1;
			tryToPut(i + 1);
			range[j] = line1[i + j] = line2[i - j + 9] = 0;
		}
	}
}
void main()
{
	tryToPut(1);
	cout <<"Cnt:"<< cnt;
}

AC_CODE:

猜你喜欢

转载自blog.csdn.net/qq_31741481/article/details/84197452
今日推荐