n皇后问题

本文介绍了一种使用深度优先搜索解决N皇后问题的方法,并详细展示了C语言实现的源代码。通过对每一步的选择进行验证,确保放置的每个皇后都不会受到攻击。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

n皇后问题

1.题意

不再叙述。

2. 源码

如下:

#include<cstdio>
#include<cstring>
#define maxn 1000
 
double array[maxn];//全局变量  保存皇后的位置 
int n;//n*n 
int count = 0;

//是否是符合条件的点  currentRow当前行 
bool isRight(int currentRow){
	int i ; 
	for(i = 1;i< currentRow;i++){
		if( array[i] == -1) break;//不符合条件的数 
		if(array[currentRow] == array[i]){
			break;//列相同 
		}
		if( ( (array[currentRow]- array[i])/(currentRow - i) == -1 ) ){
			break;//在斜对脚线上
		}
		if( ((array[currentRow]- array[i])/(currentRow - i) == 1 ) ){
			break;//在斜对脚线上
			
		}
	}
	if(i == currentRow)	return true;
	else
	 return false;
}

void dfs(int currentRow){
	if(currentRow == n+1){//如果已经到了最后一行的下一行 
		for(int j = 1;j <= n;j++){
			printf("%.0lf ",array[j]);//输出 
		} 
		printf("\n");
		count++;
		return ;//返回 
	} 
	for(int i = 1;i<= n;i++){
		array[currentRow] = i;
		if(isRight(currentRow)){//如果符合条件--->则继续 
			dfs(currentRow+1);//往下一行搜索	
		}
	}
} 
  
int main(){	
	scanf("%d",&n);
	dfs(1); 
	//printf("count = %d\n",count);
}
/**
4/3 == 1 
*/
3.更新日志

== update on 20200203== ============

对于深搜的代码应该注意如下几点:

  • 尽量先判断是否符合条件,再深搜。(而不是深搜之后再判断条件。否则有的样例是过不了的,比如络谷里的p1219 8皇后问题
  • 如果可以剪枝,则应尽量剪枝
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

说文科技

看书人不妨赏个酒钱?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值