八皇后问题 OpenJ_Bailian - 2698

传送门

代码:

方法一
#include<stdio.h>
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)
int a[10][10];//输出
int b[10][10];//判断
int number = 1;
void HH(int x, int y,int p,int q) {
	for (int i = 0; i < 8; i++) {
		if (b[x][i] == p) {
			b[x][i] = q;
		}
	}
	for (int i = 0; i < 8; i++) {
		if (b[i][y] == p) {
			b[i][y] = q;
		}
	}
	int s1 = x, s2 = y;
	while (s1 >= 0 && s1 < 8 && s2 >= 0 && s2 < 8) {
		if (b[s1][s2] == p) {
			b[s1][s2] = q;
		}
		s1--;
		s2++;
	}
	s1 = x, s2 = y;
	while (s1 >= 0 && s1 < 8 && s2 >= 0 && s2 < 8) {
		if (b[s1][s2] == p) {
			b[s1][s2] = q;
		}
		s1++;
		s2--;
	}
	s1 = x, s2 = y;
	while (s1 >= 0 && s1 < 8 && s2 >= 0 && s2 < 8) {
		if (b[s1][s2] == p) {
			b[s1][s2] = q;
		}
		s1++;
		s2++;
	}
	s1 = x, s2 = y;
	while (s1 >= 0 && s1 < 8 && s2 >= 0 && s2 < 8) {
		if (b[s1][s2] == p) {
			b[s1][s2] = q;
		}
		s1--;
		s2--;
	}
}
void DFS(int flag) {
	if (flag == 8) {
		printf("No. %d\n", number);
		number++;
		for (int i = 0; i < 8; i++) {
			for (int j = 0; j < 8; j++) {
				printf("%d ", a[j][i]);
			}
			printf("\n");
		}
	}
	else {
		for (int i = 0; i < 8; i++) {
			if (b[flag][i]==0) {
				a[flag][i] = 1;
				HH(flag, i, 0, flag + 1);
				DFS(flag + 1);
				HH(flag, i, flag+1, 0);
				a[flag][i] = 0;
			}
		}
	}
}
int main() {
	number = 1;
	DFS(0);
}

方法二
#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll long long
#define PI acos(-1)
#define mes(x,y) memset(x,y,sizeof(x))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
string s;
ll n, m, i, j, k, t=1;
ll mm[10];
void DFS(ll flag) {
	//cout << flag << endl;
	if (flag == 8) {
		cout << "No. " << t++ << endl;
		for (ll x = 0; x < 8; x++) {
			for (ll y = 0; y < 8; y++) {
				if (mm[y]==x)cout << "1 ";
				else cout << "0 ";
			}
			cout << endl;
		}
	}
	else {
		for (ll x = 0; x < 8; x++) {
			mm[flag] = x;
			bool f = true;
			for (ll y = 0; y < flag; y++) {
				if (mm[y] == mm[flag] || mm[y] - y == mm[flag] - flag || mm[y] + y == mm[flag] + flag) {
					f = false;
					break;
				}
			}
			if (f)
				DFS(flag + 1);
		}
	}
}
int main() {
	DFS(0);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

GUESSERR

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值