#include <stdio.h> #include <stdlib.h> #include <string.h> char s[5]; char e[5]; int state[10][10][10][10]; char temp[5]; char de[] = "####"; char q[10000][5]; int step; int check(char a[5]) { if (0 == state[a[0] - '0'][a[1] - '0'][a[2] - '0'][a[3] - '0']) return 0; // have not arrived else return 1; // have arrived } void bfs() { // 初始化队列 char t; int head, tail; head = 0; memcpy(q[1], s, 5); memcpy(q[2], de, 5); tail = 3; state[q[1][0] - '0'][q[1][1] - '0'][q[1][2] - '0'][q[1][3] - '0'] = 1; int i; step = 0; while (head < tail) { head++; // if (0 == strcmp(q[head], e)) return; if (0 == strcmp(de, q[head])) { memcpy(q[tail++], de, 5); step++; continue; } // for (i = 0; i < 4; i++) { memcpy(temp, q[head], 5); if (temp[i] == '9') temp[i] = '1'; else temp[i]++; if (!check(temp)) { memcpy(q[tail++], temp, 5); state[temp[0] - '0'][temp[1] - '0'][temp[2] - '0'][temp[3] - '0'] = 1; } memcpy(temp, q[head], 5); if (temp[i] == '1') temp[i] = '9'; else temp[i]--; if (!check(temp)) { memcpy(q[tail++], temp, 5); state[temp[0] - '0'][temp[1] - '0'][temp[2] - '0'][temp[3] - '0'] = 1; } } for (i = 0; i < 3; i++) { memcpy(temp, q[head], 5); t = temp[i]; temp[i] = temp[i + 1]; temp[i + 1] = t; if (!check(temp)) { memcpy(q[tail++], temp, 5); state[temp[0] - '0'][temp[1] - '0'][temp[2] - '0'][temp[3] - '0'] = 1; } } } } int main() { int n; scanf("%d", &n); while (n--) { scanf("%s", &s); scanf("%s", &e); memset(state, 0, sizeof(state)); memset(q, 0, sizeof(q)); bfs(); printf("%d\n", step); } return 0; }
hduoj_1195(bfs)
猜你喜欢
转载自blog.csdn.net/qq_32862515/article/details/80699278
今日推荐
周排行