八皇后问题

时间限制:1秒        内存限制:128M

题目描述

在国际象棋棋盘上放置八个皇后,要求每两个皇后之间不能直接吃掉对方。

输入描述

(无)

输出描述

按给定顺序和格式输出所有八皇后问题的解(见样例)。

提示:按行进行的搜索

样例输出

No. 1
1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
No. 2
1 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1
0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0
……
No. 92
0 0 0 0 0 0 0 1
0 0 0 1 0 0 0 0
1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
#include<bits/stdc++.h>
using namespace std;
int chess[10][10],cnt;
void print(int x,int y) {
	cnt++;
	cout<<"No. "<<cnt<<endl;
	for(int i=1; i<=x; i++) {
		for(int j=1; j<=y; j++) {
			cout<<chess[i][j]<<" ";
		}
		cout<<endl;
	}
}
bool check(int x,int y) {
	for(int i=1; i<x; i++) {
		if(chess[i][y]==1) {
			return 0;
		}
	}
	for(int i=x-1,j=y-1; i>=1&&j>=1; i--,j--) {
		if(chess[i][j]==1) {
			return 0;
		}
	}
	for(int i=x-1,j=y+1; i>=1&&j<=8; i--,j++) {
		if(chess[i][j]==1) {
			return 0;
		}
	}
	return 1;
}
void dfs(int row) {
	if(row>8) {
		print(8,8);
		return;
	}
	for(int i=1; i<=8; i++) {
		if(check(row,i)) {
			chess[row][i]=1;
			dfs(row+1);
			chess[row][i]=0;
		}
	}
}
int main() {
	dfs(1) ;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值