hdu2553 N皇后问题 dfs+打表

时间:2019-09-13
本文章向大家介绍hdu2553 N皇后问题 dfs+打表,主要包括hdu2553 N皇后问题 dfs+打表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

N皇后问题

Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。

Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
 
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
 
Sample Input
1
8
5
0
Sample Output
1
92
10
#include <bits/stdc++.h>
using namespace std;
int n,tot=0;
int col[12]={0};
bool check(int c,int r ){ //当前坐标 (r,c) 
	for(int i=0;i<r;i++){
		if(col[i]==c ||  abs( col[i]-c)== abs(i-r)  ) return false;
	}
	return true;
}
void dfs(int r){
	if(r==n) {
		tot++;
		return ;
	}
	for(int c=0;c<n;c++){
		if( check(c,r)){
			col[r]=c;
			dfs(r+1);
		}
	}
}
int main(){
	int ans[12]={0};
	for(n=0;n<=10;n++){
		tot=0;
		memset(col,0,sizeof(col)  );
		dfs(0);
		ans[n]=tot;
	}
	while(~scanf("%d",&n)&&n){
		cout<<ans[n]<<endl;
	}	
	return 0;
}

  

 
 

原文地址:https://www.cnblogs.com/lyj1/p/11516914.html