八皇后

描述

会下国际象棋的人都很清楚:皇后可以在横、竖、斜线上不限步数地吃掉其他棋子。如何将8个皇后放在棋盘上(有8 × 8个方格),使它们谁也不能被吃掉!这就是著名的八皇后问题。

对于某个满足要求的8皇后的摆放方法,定义一个皇后串a与之对应,即a=b1b2...b8,其中bi为相应摆法中第i行皇后所处的列数。已经知道8皇后问题一共有92组解(即92个不同的皇后串)。

给出一个数b,要求输出第b个串。串的比较是这样的:皇后串x置于皇后串y之前,当且仅当将x视为整数时比y小。

格式

输入格式

第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数b(1≤b≤92)。

输出格式

输出有n行,每行输出对应一个输入。输出应是一个正整数,是对应于b的皇后串。

样例

输入样例

2
1
92

输出样例

15863724
84136275

利用深搜的思路写

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
int map[9][9];
int ans[1000][9];

int cnt;

void initMap(){
	for(int i=1; i<=8; ++i){
		for(int j=1; j<=8; ++j){
			map[i][j] = 0;
		}
	}
}
void showMap(){
	for(int i=1; i<=8; ++i){
		for(int j=1; j<=8; ++j){
			printf("%d ",map[i][j]);
		}
		printf("\n");
	}
}

//判断这个地方能不能放皇后 
int verify(int row, int col){	
	
	for(int i=1; i<=8; ++i){
		if( map[row][i] == 1 || map[i][col] == 1){
			return 0;
		}
	}
	int y,x;
	y = row, x = col;
	while(y>=1 && x>=1){
		if(map[y--][x--] == 1){
			return 0;
		}
	}
	y = row, x = col;
	while(y<=8 && x<=8){
		if(map[y++][x++] == 1){
			return 0;
		}
	}
	y = row, x = col;
	while(y<=8 && x>=1){
		if(map[y++][x--] == 1){
			return 0;
		}
	}
	y = row, x = col;
	while(y>=1 && x<=8){
		if(map[y--][x++] == 1){
			return 0;
		}
	}
	
	return 1;
}

void fun(int row, int col, int arr[]){
	
	if( verify(row, col) == 0){
		return ;
	}
	map[row][col] = 1;
	arr[row] = col;
		
	for(int i=1; i<=8; ++i){
		fun(row+1, i, arr);
	}
	
	if(row == 8){		
		for(int i=1; i<=8; ++i){
			ans[cnt][i] = arr[i];
		}		
		
		cnt++;
	}

	map[row][col] = 0;	
	
}
int main(){

	initMap();
	int arr[10];
	arr[1] = 1;
	cnt = 1;
	for(int i=1; i<=8; ++i){
		fun(1, i, arr);			
	}
	
	
	int n,x;
	cin>>n;
	while(n--){
		cin>>x;
		for(int i=1; i<=8; ++i){
			printf("%d",ans[x][i]);
		}
		printf("\n");
	}
	

	return 0;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值