问题 D: N皇后 回溯

在这里插入图片描述

思路

同一排同一列和斜45度不能放
也就是米字上没有其他皇后
如果米字范围内有其他皇后则跳过
再搜索

代码

#include<bits/stdc++.h>
using namespace std;
int ans;
int n;
char s[15][15];
int dir[4][2]={{-1,1},{1,-1},{-1,-1},{1,1}};	//四个方向
void init(int n){			//数组初始化
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++){
			s[i][j]='.';
		}
	}
}
bool check(int x,int y){   //检查函数
	for(int i=0;i<y;i++){  //检查列
		if(s[x][i]=='Q')
			return false;
	}
	for(int i=0;i<x;i++){	//检查行
		if(s[i][y]=='Q')
			return false;
	}
	for(int i=0;i<4;i++){	//检查四个方向
		int tx=x;
		int ty=y;
		while(tx>=0&&ty>=0&&tx<n&&ty<n){	//保证没有超出棋盘
			if(s[tx][ty]=='Q'){
				return false;
			}
			tx+=dir[i][0];	
			ty+=dir[i][1];
		}
	}
	return true;
}
void dfs(int cow){
	if(cow==n){
		ans++;
		return;
	}
	for(int i=0;i<n;i++){
		if(check(cow,i)){
			s[cow][i]='Q';
			dfs(cow+1);
			s[cow][i]='.';//回溯,把'Q' 变回'.'
		}
	}
}
int main()
{	
	while(cin>>n){
	
		int a[15];
		for(int i=0;i<11;i++)
		{
			init(n);
			ans=0;
			dfs(0);
			a[i]=ans;
		}
		cout<<a[n]<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值