P2324 [SCOI2005]骑士精神(IDA*)

题目大意:

在这里插入图片描述
在这里插入图片描述
(来源:洛谷)

解题思路:

其实就相当于八数码难题把,估价函数都一样,感觉用A星也可以做,为了练习,还是用了IDA*

  • 其实就多了判断当前剩余层次是否够用就行了
if (maxd + 1 - d < h(cur)) return false;

AC代码:

#include<bits/stdc++.h>
using namespace std;
char goal[10][10] = {{"11111"}, {"01111"}, {"00*11"}, {"00001"}, {"00000"}};
char cur[10][10];
int x[8] = {-1, -1, 1, 1, -2, -2, 2, 2}, y[8] = {-2, 2, -2, 2, 1, -1, 1, -1};
int T, maxd;
int h(char now[10][10]) {
	int cnt = 0;
	for (int i = 0; i < 5; i++)
		for (int j = 0; j < 5; j++)
			if (now[i][j] != goal[i][j] && goal[i][j] != '*')
				cnt++;
	return cnt;
}
bool dfs(int d, int tx, int ty) {
	if (d == maxd + 1) {
		if (!h(cur)) return true;
		else return false;
	}
	if (maxd + 1 - d < h(cur)) return false;
	for (int i = 0, nx, ny; i < 8; i++) {
		nx = tx + x[i], ny = ty + y[i];
		if (nx < 0 || nx > 4 || ny < 0 || ny > 4) continue;
		swap(cur[tx][ty], cur[nx][ny]);
		if (dfs(d + 1, nx, ny)) {
			return true;
		}
		swap(cur[nx][ny], cur[tx][ty]);
	}
	return false;
}
int main() {
	cin >> T;
	while (T--) {
		int tx, ty;
		for (int i = 0; i < 5; i++)
			for (int j = 0; j < 5; j++) {
				cin >> cur[i][j];
				if (cur[i][j] == '*') tx = i, ty = j;
			}	
		bool ok = false;
		for (maxd = 0; maxd <= 15; maxd++) {
			if (dfs(1, tx, ty)) {
				ok = true;
				break;
			}
		}
		if (ok) cout << maxd << endl;
		else cout << -1 << endl;
	}
}
/*
1
11111
01111
10010
00001
000*0
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值