1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 x
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8
9 x 10 12 9 10 x 12 9 10 11 12 9 10 11 12
13 14 11 15 13 14 11 15 13 14 x 15 13 14 15 x
r-> d-> r->
Input
1 2 3
x 4 6
7 5 8
1 2 3 x 4 6 7 5 8
Output
Sample Input
2 3 4 1 5 x 7 6 8
Sample Output
ullddrurdllurdruldr
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #define MAXN 500000 5 using namespace std; 6 char input[30]; 7 int state[9], goal[9] = {1,2,3,4,5,6,7,8,0}; 8 int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; // 上,下,左, 右 9 char path_dir[5] = "udlr"; 10 int st[MAXN][9]; 11 int father[MAXN], path[MAXN]; // 保存打印路径 12 13 const int MAXHASHSIZE = 1000003; 14 int head[MAXHASHSIZE], next[MAXN]; 15 16 void init_lookup_table() { memset(head, 0, sizeof(head)); } 17 18 typedef int State[9]; 19 int hash(State& s) { 20 int v = 0; 21 for(int i = 0; i < 9; i++) v = v * 10 + s[i]; 22 return v % MAXHASHSIZE; 23 24 } 25 26 int try_to_insert(int s) { 27 int h = hash(st[s]); 28 int u = head[h]; 29 while(u) { 30 if(memcmp(st[u], st[s], sizeof(st[s])) == 0) return 0; 31 u = next[u]; 32 } 33 next[s] = head[h]; 34 head[h] = s; 35 return 1; 36 } 37 38 int bfs(){ 39 init_lookup_table(); 40 father[0] = path[0] = -1; 41 int front=0, rear=1; 42 memcpy(st[0], state, sizeof(state)); 43 44 while(front < rear){ 45 int *s = st[front]; 46 47 if(memcmp(s, goal, sizeof(goal))==0){ 48 return front; 49 } 50 51 int j; 52 for(j=0; j<9; ++j) if(!s[j])break; // 找出0的位置 53 int x=j/3, y=j%3; // 转换成行,列 54 55 for(int i=0; i<4; ++i){ 56 57 int dx = x+dir[i][0]; // 新状态的行,列 58 int dy = y+dir[i][1]; 59 int pos = dx*3+dy; // 目标的位置 60 61 if(dx>=0 && dx<3 && dy>=0 && dy<3){ 62 int *newState = st[rear]; 63 memcpy(newState, s, sizeof(int)*9); 64 newState[j] = s[pos]; 65 newState[pos] = 0; 66 if(try_to_insert(rear)){ 67 father[rear] = front; path[rear] = i; 68 rear++; 69 } 70 } 71 } 72 front++; 73 } 74 return -1; 75 } 76 77 void print_path(int cur){ 78 if(cur!=0){ 79 print_path(father[cur]); 80 printf("%c", path_dir[path[cur]]); 81 } 82 } 83 84 int main(){ 85 86 while(gets(input)){ 87 // 转换成状态数组, 'x'用0代替 88 for(int pos=0, i=0; i<strlen(input); ++i){ 89 if(input[i]>='0' && input[i]<='9') 90 state[pos++] = input[i]-'0'; 91 else if(input[i]=='x') 92 state[pos++] = 0; 93 } 94 int ans; 95 if((ans=bfs())!=-1){ 96 print_path(ans); 97 printf("\n"); 98 } 99 } 100 }