洛谷P1219 [USACO1.5]八皇后 Checker Challenge

  • Post author:
  • Post category:其他


分析:

可知每行必定只有一个皇后,所以一行一行历遍搜索即可,采用dfs。你只需要去判断这个(x,y)这个位置下他是否可以放下皇后,但是如果你用一个n*m的数组去代表他每个位置下的状态的话,这很显然是会超时的,所以重看提议我们可以发现,皇后所在的行与列,和左右的斜列是不可以的放置的,所以我们可以设定4个数组,分别代表行,列,左斜列与右斜列。如何判断同行同列不需要过多的讲述,相同左斜列相减值相同,相同右斜列相加值相同。所以就此我们便可以给出如下代码

注:头文件部分属于笔者习惯,无需在意。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<set>
#include<vector>
#include<stdlib.h>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include <cstring>
#define ll long long
using namespace std;
bool row[14];
bool col[14];
bool r[100];
bool l[100];
vector<int> path;
vector<vector<int>> res;
int ans = 0;
bool is_vaild(int x, int y, int size) {
	if (row[x] || col[y] || r[x + y] || l[x - y + size]) {
		return false;
	}
	return true;
}
void solution(int size,int startindex) {
	if (startindex > size) {
		ans++;
		res.push_back(path);
		return;
	}
		for (int j = 1; j <= size; j++) {
			if (is_vaild(startindex,j,size)) {
				path.push_back(j);
				row[startindex] = 1, col[j] = 1, r[startindex + j] = 1, l[startindex - j + size] = 1;
				solution(size, startindex + 1);
				row[startindex] = 0, col[j] = 0, r[startindex + j] = 0, l[startindex - j + size] = 0;
				path.pop_back();
			}
		}
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	int size;
	cin >> size;
	solution(size, 1);
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < size; j++) {
			if (j == 0)cout << res[i][j];
			else {
				cout << " " << res[i][j];
			}
		}
		cout << "\n";
	}
	cout << ans << endl;
}



版权声明:本文为brokyyyyy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。