HDU2553N皇后问题题解

Problem Description

在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。

Input

共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。

Output

共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。

Sample Input

1
8
5
0

Sample Output

1
92
10

Author

cgf

Source

2008 HZNU Programming Contest

思路

普通的N皇后问题。
时间复杂度很狗。
本蒟蒻用了不讲狗德的打表(自己编的程序算出解在打表)。
主要是TLE了。
他的时间卡的很死。
其实可以在程序的开头把1 - 10 的情况都写出来。

AC代码

#include <iostream>
#include <cmath>

using namespace std;

int n, ans;
int x[20];

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

void dfs(int step) {
	if (step > n) {
		ans++;
	} else {
		for (int i = 1; i <= n; i++) {
			x[step] = i;
			if (check(step)) {
				dfs(step + 1);
			}
		}
	}
}

int main() {
	while (1) {
		ans = 0;
		cin >> n;
		if (!n) break;
		dfs(1);
		cout << ans << endl;
	}
	return 0;
}

打表

#include <iostream>
#include <cmath>

using namespace std;

int n, ans;
int x[20] = {0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724};
int main() {
	while (1) {
		ans = 0;
		cin >> n;
		if (!n) break;
		cout << x[n] << endl;
	}
	return 0;
}

整合代码

#include <iostream>
#include <cmath>

using namespace std;

int n, ans;
int x[20], ans[20];

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

void dfs(int step) {
	if (step > n) {
		ans++;
	} else {
		for (int i = 1; i <= n; i++) {
			x[step] = i;
			if (check(step)) {
				dfs(step + 1);
			}
		}
	}
}

int main() {
	for (int i = 1; i <= 10; i++) {
		ans[i] = dfs(i);
	}
	while (1) {
		ans = 0;
		cin >> n;
		if (!n) break;
		cout << ans[n] << endl;
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值