UVA - 10085 The most distant state 隐式图搜索

题目大意:给你一个初始状态的8数码,要求你求出这个八数码的移动的最大步数,使其出现以前的状态,并输出移动路径

解题思路:这题和八数码的原题相似,只不过这是没有最终状态的,要满足 rear==front才会使其达到最大值,再创数组保存路径

#include<cstdio>
#include<cstring>
#define maxn 5000000
#define HASH_SIZE 10000003
int head[HASH_SIZE], next[HASH_SIZE];
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
typedef int Statu[9];
Statu S[maxn],start,last;
int father[maxn],move[maxn],ans;
char b[5] = {'U','D','L','R'};

int hash(Statu cur) {

	int s = 0;
	for(int i = 0; i < 9; i++)
		s = s * 10 + cur[i];
	return s % HASH_SIZE;
}

bool try_insert(int s) {

	int h = hash(S[s]);
	int v = head[h];
	while(v) {
		if(memcmp(S[v],S[s],sizeof(S[s])) == 0)
			return false;
		v = next[v];	
	}

	next[s] = head[h];
	head[h] = s;
	return true;
}

void BFS() {

	memset(head,0,sizeof(head));
	memcpy(S[0],start,sizeof(start));
	int front = 0, rear = 1;
	while(rear > front) {
		Statu &t = S[front];
		memcpy(last,t,sizeof(last));
		int z;
		for(z = 0; z < 9; z++)
			if(!t[z])
				break;
		int x = z / 3;
		int y = z % 3;
		for(int i = 0; i < 4; i++) {
			int newx = x + dir[i][0];
			int newy = y + dir[i][1];
			int newz = newx * 3 + newy;
			if(newx >= 0 && newx < 3 && newy >= 0 && newy < 3) {

				Statu &s = S[rear];
				memcpy(s,t,sizeof(t));
				s[newz] = t[z];
				s[z] = t[newz];
				if(try_insert(rear)) {
					father[rear] = front;
					move[rear] = i;
					rear++;
				}
			}
		}	
		front++;
	}
	ans = rear-1;
}

void print_path(int cur) {
	if(cur == 0)
		return ;
	print_path(father[cur]);
	printf("%c",b[move[cur]]);

}
int main() {

	int test, mark = 1;
	scanf("%d",&test);
	while(test--) {
		for(int i = 0; i < 9; i++)
			scanf("%d",&start[i]);
		BFS();
		printf("Puzzle #%d\n",mark++);
		for(int i = 0; i < 3; i++)
			printf("%d %d %d\n",last[i*3],last[i*3+1],last[i*3+2]);
		print_path(ans);
		printf("\n\n");
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值