跳到正文

题解

八皇后问题

Vectg7约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月23日
更新
2025年12月23日
篇幅
约 1 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
int a[10][10],cnt;
void print(){
	cout<<"No."<<setw(2)<<cnt<<'\n';
	for(int i=1;i<=8;i++)for(int j=1;j<=8;j++)cout<<a[i][j]<<(j==8?'\n':' ');}
bool check(int x,int y){
	for(int i=1;i<=8;i++)if(a[i][y])return 0;
	for(int i=1;i<=8;i++)for(int j=1;j<=8;j++)if((i-j==x-y||i+j==x+y)&&a[i][j])return 0;
	return 1;}
void dfs(int r){
	if(r==9){
		cnt++;
		print();
		return ;}
	for(int j=1;j<=8;j++){
		if(check(r,j)){
			a[r][j]=1;
			dfs(r+1);
			a[r][j]=0;}}}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	dfs(1);}
原文