时间限制: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;
}

1万+

被折叠的 条评论
为什么被折叠?



