n皇后问题

本文介绍了一种使用一维数组解决N皇后问题的方法,并提供了一个C++实现示例。通过递归的方式,从第一行开始放置皇后,确保任意两个皇后不在同一行、列或对角线上。

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

Description

Given N queens on an N*N chess board, find the number of ways of placing these queens so that they will not attack each other.

 

Input

There are multiple cases. For each case, there is only one line given the number of queens N (1<=N<=9).

Output

For each case, output the number of all possible placements of queens.

Sample Input
Copy sample input to clipboard
4
Sample Output
2

用一维数组做的x[t]=I,表示的是第T行I列放置了一个皇后,而且我们是从第一行开始放皇后的,每放完就判断放完后会不会互相攻击,如果不会就递归放下一个,直到放置的皇后数达到我们的要求,判断会不会攻击的方法也比较简单,因为我们是逐行放皇后的,所以不会存在行冲突,所以我们只需要跟前面放完的那几行判断列冲突,即x[k]==x[i],以及对角冲突abs(k-i)==abs(x[k]-x[i])这两种就好

#include <iostream>
#include <cmath>
using namespace std;

int n;	//皇后个数 
int sum=0;	//有多少个解 
int x[11];	//放置在第几列 

int place(int k){
	int i;
	for(int i=1; i < k; ++i){
		if(abs(k-i)==abs(x[k]-x[i])||x[k]==x[i]) return false; 
	}
	return true;
}

int queen(int t){//t为放置第几个皇后 
	if(t>n&&n>0)//如果放置皇后超过我们需要,则该解满足,应加一 
		sum++;
	else{
		for(int i=1; i <= n; ++i){
			x[t]=i;//第t个皇后放置在第i列 
			if(place(t)){
				queen(t+1);
			}
		}
	}
	return sum;
}

int main()
{
	while(cin >> n){
		sum=0;
		int res=queen(1);
		if(n==0) cout << 0 << endl;
		else cout << res << endl;
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值