八皇后的另类写法 HDU - 2553 — 自己的想法很独特

八皇后有很多种写法:

1 回溯法:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<iomanip>
#define FAST ios::sync_with_stdio(fasle)
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = (int)1e9 + 7;
const int maxn = (int)1e5 + 5;
using namespace std;
 
int c[10];//数组c表示在第x行皇后的列编号,即pos = (x, c[x])
int arr[10][10];
int cnt = 0;
 
void solve(int cur){
	if(cur == 8) cnt++;
	else{
		for(int i = 0; i < 8; i++){
			bool flag = true;
			c[cur] = i;
			for(int j = 0; j < cur; j++)
				if(c[cur] == c[j] || cur - c[cur] == j - c[j] || cur + c[cur] == j + c[j]){
					flag = false;
					break;
				}
				if(flag) solve(cur+1);
		}
	}
}
 
int main()
{
	solve(0);
	cout << cnt << endl;
	return 0;
}
 
	/*for(int i = 0; i < 8; i++)
			for(int j = 0; j < 8; j++)
				arr[i][j] = 0;
		for(int i = 0; i < 8; i++){
			arr[i][c[i]] = 1;
		}
		for(int i = 0; i < 8; i++){
			for(int j = 0; j < 8; j++){
				cout << arr[i][j] << ' ';
			}
			cout << endl;
		}
		cout << "---------------------------" << endl;*/

 

2   我自己发现的另一种写法:

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
int a[100],b[100],c[100],d[100];   //a数组表示的是行; //b数组表示的是列; //c表示的是左下到右上的对角线; //d表示的是左上到右下的对角线;
int total;//总数:记录解的总数
int n;//输入的数,即N*N的格子,全局变量,搜索中要用

void queen(int i)//搜索与回溯主体
{
	if(i>n)
	{
		total++;
		return;
	}
	else
	{
		for(int j = 1;j <= n;j++)//尝试可能的位置
		{
			if(( !b[j] ) && ( !c[i+j] ) && ( !d[i-j+n] ))//如果没有皇后占领,执行以下程序
			{
				a[i] = j;//标记i排是第j个
				b[j] = 1;//宣布占领纵列
				c[i + j] = 1;
				d[i - j + n] = 1;//宣布占领两条对角线
				queen(i + 1);//进一步搜索,下一个皇后
				b[j] = 0;
				c[i+j] = 0;
				d[i - j + n] = 0;//(回到上一步)清除标记 
			}
		}
	}
}
int main()
{
	while(cin >> n)
	{
		if(n == 0) continue;

		total = 0;
		//输入N*N网格,n已在全局中定义 
	queen(1);//第一个皇后
	cout << total << endl;//输出可能的总数 
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值