题目大意:给你一个初始状态的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;
}









