搜索_常规DFS_HDOJ2553_N皇后问题

版权声明:本文为博主原创作品, 转载请注明出处! https://blog.csdn.net/solider98/article/details/85519897

点此打开题目页面

思路分析: 直接使用DFS并使用适当的剪枝策略即可, 具体实现如下AC代码所示:

//HDOJ2553_N皇后问题
#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;
const int MAX = 20;
int N; bool used[MAX];//used[i]: true第i列已经被占用
int cnt[MAX];//cnt[i]: N = i时的方案数 
bool ok[MAX];//ok[i]: true:N = i已经计算过 
//path[i]: 第i行皇后所在列 
void dfs(vector<int> &path){
	if(path.size() == N){
		++cnt[N]; return;
	}	
	for(int i = 1; i <= N; ++i){
		if(!used[i]){
			for(int j = 0; j < path.size(); ++j)
				if(abs(path[j] - (double)i) == abs(path.size() + (double)1 - (j + 1))) 
					goto GO1;
			path.push_back(i), used[i] = true, dfs(path)
			, path.pop_back(), used[i] = false;
		}
		GO1: ;
	}
}
int main(){
	while(scanf("%d", &N), N){
		if(ok[N]){
			cout << cnt[N] << endl;
			continue;
		}
		vector<int> path; dfs(path), ok[N] = true;
		cout << cnt[N] << endl; 
	}
}

猜你喜欢

转载自blog.csdn.net/solider98/article/details/85519897