首页 > 其他 > 详细

hdu2553 N皇后问题 dfs+打表

时间:2019-09-13 17:15:10      阅读:66      评论:0      收藏:0      [点我收藏+]

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

  

 
 
 

 

 

hdu2553 N皇后问题 dfs+打表

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!