N皇后问题
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 29378    Accepted Submission(s): 12879
Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1
8
5
0
Sample Output
1
92
10
Author
cgf
Source
Recommend
#include <iostream>
#include <cmath>
using namespace std;
int set[13];  //放置纵坐标 
int n, sum; 
int zl[13];
void dfs(int x){	
	if(x > n){
		sum++;
		return ;
	} 
	for(int y = 1; y <= n; y++){     //枚举每一列 
		int i;
		for(i = 1; i < x; i++){  //检测该列 
			if(set[i] == y)
				break;
		} 
		if(i < x){ //列有人 
			continue;
		}
		for(i = 1; i < x; i++){  //检测对角线,通过斜率绝对值为1来判断 
			if(x - i == abs(y - set[i]))   
				break;
		} 
		if(i < x){
			continue;
		} 
		set[x] = y; //找到了合适的列,填进去 
		dfs(x + 1);
	} 
}
int main(){
	std::ios::sync_with_stdio(false); 
	for(n = 1; n <= 10; n++){
		sum = 0;
		dfs(1);  //每次从第一行放起 
		zl[n] = sum;
	}
	while(cin >> n && n){
		cout << zl[n] << endl;
	} 
	return 0;
} 
                    
                
                
            
        
浙公网安备 33010602011771号