hdu2553 N queens problem dfs + play table

N Queens

Problem Description
In the checkerboard-N * N N queens placed such that they do not attack each other (i.e., does not allow any two queens in the same row, same column, is not allowed in the board frame 45 on a diagonal angle .
your task is, for a given N, how many legitimate method of obtaining placed there.

Input
There are several lines of a positive integer n ≤ 10, and represents the number of Queen board; if N = 0, indicating the end.
 
Output
There are a number of lines, each a positive integer representing the number of different placement Queen corresponding input line.
 
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;
}

  

 
 
 

 

 

Guess you like

Origin www.cnblogs.com/lyj1/p/11516914.html