【POJ1077】Eight【IDA*】

【题目链接】

学习一发IDA*。

/* Pigonometry */
#include <cstdio>
#include <iostream>

using namespace std;

const int maxn = 4, maxm = 105, inf = 0x3f3f3f3f;

char opt[] = {'u', 'd', 'l', 'r'};
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

int mp[maxn][maxn], ed[maxn][maxn];
bool found;
char solu[maxm];

inline int read() {
	char ch = getchar(); for(; !(ch == 'x' || (ch >= '0' && ch <= '9')); ch = getchar());
	return ch == 'x' ? 0 : ch - '0';
}

inline int intabs(int x) {
	return x < 0 ? -x : x;
}

inline int getH() {
	int res = 0;
	for(int i = 1; i <= 3; i++) for(int j = 1; j <= 3; j++) if(mp[i][j]) {
		int x = (mp[i][j] - 1) / 3 + 1, y = (mp[i][j] - 1) % 3 + 1;
		res += intabs(i - x) + intabs(j - y);
	}
	return res;
}

inline int dfs(int x, int y, int d, int lim) {
	int h = getH();
	if(h == 0 || found) {
		found = 1;
		return d;
	}
	if(d + h > lim) return d + h;

	int nowlim = inf;
	for(int i = 0; i < 4; i++) {
		int xx = x + dx[i], yy = y + dy[i];
		if(xx < 1 || xx > 3 || yy < 1 || yy > 3) continue;
		swap(mp[x][y], mp[xx][yy]);
		solu[d] = opt[i];
		int nextlim = dfs(xx, yy, d + 1, lim);
		nowlim = min(nowlim, nextlim);
		if(found) return nowlim;
		swap(mp[x][y], mp[xx][yy]);
	}
	return nowlim;
}

int main() {
	int sx, sy;
	for(int i = 1; i <= 3; i++) for(int j = 1; j <= 3; j++) {
		mp[i][j] = read();
		if(!mp[i][j]) sx = i, sy = j;
		ed[i][j] = (i - 1) * 3 + j;
	}
	ed[3][3] = 0;

	found = 0;
	int deplim = getH();
	while(deplim < 100 && !found) deplim = dfs(sx, sy, 0, deplim);

	if(!found) printf("unsolvable\n");
	else {
		solu[deplim] = '\0';
		printf("%s", solu);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值