八皇后 递归+循环

八皇后

递归实现

#include <iostream>
#include <algorithm>
#include <cmath>
#define maxn 1005

using namespace std;
int a[maxn];
int n;
int cnt = 0;
int path[maxn][maxn];
void queen(int step);
int check(int k);
int main() {
	cin >> n;
	queen(0);
	cout << cnt << endl;

	system("pause");
	return 0;
}

void queen(int step) {
	if (step >= n) {
		cnt++;
		cout << "No." << cnt << ":" << endl;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				cout << path[j][i] << " ";
			}
			cout << endl;
		}
		cout << endl;
	}
	for (int i = 0; i < n; i++) {
		a[step] = i;

		if (path[step][i] != 1 && check(step)) {
			path[step][i] = 1;
			queen(step + 1);
			path[step][i] = 0;
		}

	}
}

int check(int k) {
	for (int i = 0; i < k; i++) {
		if (abs(i - k) == abs(a[i] - a[k]) || a[i] == a[k]) {
			return 0;
		}
	}
	return 1;
}

迭代实现

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#define maxn 1005

using namespace std;
int x[maxn];
int n;
int sum = 0;
void backtrack();
int check(int i);
int main() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		x[i] = 0;
	}
	backtrack();


	system("pause");
	return 0;
}

void backtrack() {
	x[1] = 0;
	int k = 1;
	while (k > 0) {
		x[k] += 1;
		while (x[k] <= n && !check(k)) {
			x[k] += 1;
		}
		if (x[k] <= n) {
			if (k == n) {
				sum++;
				cout << "No." << sum << ":" << endl;
				for (int i = 1; i <= n; i++) {
					cout << x[i] << " ";
				}
				cout << endl;
			}
				
			else {
				k++;
				x[k] = 0;
			}
		}
		else {
			k--;
		}
			
	}
}

int check(int i) {
	for (int j = 1; j < i; j++) {
		if ((abs(i - j) == abs(x[i] - x[j])) || (x[i] == x[j])) {
			return 0;
		}
	}
	return 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值