短学期Day.6(搜索)

https://www.luogu.com.cn/problem/P1219(八皇后问题)

#include<iostream>
using namespace std;
int n, a[1000], b[1000], c[1000], d[1000], s;
void search(int i) {
	
	
		for (int j = 1; j <= n; j++) {
			if (b[j] == 0 && c[i + j] == 0 && d[i - j + n] == 0) {
				a[i] = j;
				b[j] = 1;
				c[i + j] = 1;
				d[i - j + n] = 1;
				if (i == n) {
					s++;
					if (s <= 3) {
						for (int i = 1; i <= n; i++) {
							cout << a[i] << " ";
						}
						cout << endl;
					}
				}
				else search(i + 1);
				b[j] = 0;
				c[i + j] = 0;
				d[i - j + n] = 0;
			}
		}
	
}
int main() {
	cin >> n;
	search(1);
	cout << s << endl;
	return 0;
}

解题关键:回溯
https://www.luogu.com.cn/problem/P1135

#include<iostream>
#include<algorithm>
using namespace std;
int p[205], t[205];
int n, a, b, ans=0x7ffffff;
void my_find(int i,int x) {
	if (i == b) {
		ans = min(ans, x);
	}
	if (x > ans) {
		return;
	}
	//t[i] = 1;
	if (i + p[i] <= n && t[i + p[i]] == 0) {
		t[i + p[i]] = 1;
		my_find(i + p[i], x + 1);
		t[i + p[i]] = 0;
	}

	if (i - p[i] >= 0 && t[i - p[i]] == 0) {
		t[i - p[i]] = 1;
		my_find(i - p[i], x + 1);
		t[i - p[i]] = 0;
	}
	//t[i] = 0;
}
int main() {
	
	cin >> n >> a >> b;
	int i;
	for (i = 1; i <= n; i++) {
		cin >> p[i];
	}
	my_find(a, 0);
	if (ans != 0x7ffffff) {
		cout << ans << endl;
	}
	else {
		cout << "-1" << endl;
	}
	return 0;
}
//重要的事情说三遍:回溯,回溯,回溯
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值