-->
当前位置:首页 > 题库 > 正文内容

7-22 n queens (10 分)

Luz4年前 (2021-03-05)题库1526
7-22 n queens (10 分)

there is a chess board with n rows and n columns, you need place n queens in the board,there are no two queens in the same line(include diagonals).

input specification:

input one integer n denotes n queens .

output specification:

place one solution in one line(for example,in the 4 queens,one solution is 2 4 1 3,that means the first row queen will be placed in the 2nd column,the 2nd row queen will be placed in the 4th column,and so on),and output the total solution number in the last line.

input example:

4

output example:

2 4 1 3 
3 1 4 2 
2
作者
严华云
单位
湖州师范学院
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include<bits/stdc++.h>
using namespace std;
int n,num[100];
int cnt=0;
int visit[100]={0};
bool judge(int t){
	for(int i=1;i<t;i++){
		if((num[i]==num[t])||(i-num[i]==t-num[t])||(i+num[i]==t+num[t])){
			return false;
		}
		
	}
	return true;
} 
void pailie(int t){
	int i,j;
	if(t>n){
		for(j=1;j<=n;j++){
			cout<<num[j]<<" ";
		}
		cnt++;
		cout<<endl;
	}
	else{
		for(i=1;i<=n;i++){
			num[t]=i;
			if(judge(t)){
				pailie(t+1);
			}
		}
	}
}

int main(){
	cin>>n;
	pailie(1);
	cout<<cnt;
}


发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。