/* Author: ACb0y Date: 2010-9-21 Type: search(bfs) ProblemId: hdu 1195 Open the Lock Result: AC */ #include <iostream> #include <string> #include <queue> using namespace std; struct node { char digit[5]; int step; }; //记忆化搜索 int mark[11][11][11][11]; char a[5], b[5]; //广度优先搜索 void bfs() { int i; node cur, q; queue<node> Queue; strcpy(q.digit, a); q.step = 0; Queue.push(q); memset(mark, 0, sizeof(mark)); while (!Queue.empty()) { cur = Queue.front(); Queue.pop(); mark[cur.digit[0] - '0'][cur.digit[1] - '0'][cur.digit[2] - '0'][cur.digit[3] - '0'] = 1; //四个位数 for (i = 0; i < 4; i++) { //加一 strcpy(q.digit, cur.digit); q.step = cur.step + 1; q.digit[i] = cur.digit[i] + 1; if (q.digit[i] == '9' + 1) { q.digit[i] = '1'; } if (mark[q.digit[0] - '0'][q.digit[1] - '0'][q.digit[2] - '0'][q.digit[3] - '0'] == 0) { if (strcmp(q.digit, b) == 0) { printf("%d/n", q.step); return; } else { mark[q.digit[0] - '0'][q.digit[1] - '0'][q.digit[2] - '0'][q.digit[3] - '0'] = 1; Queue.push(q); } } //减一 strcpy(q.digit, cur.digit); q.step = cur.step + 1; q.digit[i] = cur.digit[i] - 1; if (q.digit[i] == '0') { q.digit[i] = '9'; } if (mark[q.digit[0] - '0'][q.digit[1] - '0'][q.digit[2] - '0'][q.digit[3] - '0'] == 0) { if (strcmp(q.digit, b) == 0) { printf("%d/n", q.step); return; } else { mark[q.digit[0] - '0'][q.digit[1] - '0'][q.digit[2] - '0'][q.digit[3] - '0'] = 1; Queue.push(q); } } //交换 if (i < 3) { strcpy(q.digit, cur.digit); char temp = q.digit[i]; q.digit[i] = q.digit[i + 1]; q.digit[i + 1] = temp; q.step = cur.step + 1; if (mark[q.digit[0] - '0'][q.digit[1] - '0'][q.digit[2] - '0'][q.digit[3] - '0'] == 0) { if (strcmp(q.digit, b) == 0) { printf("%d/n", q.step); return; } else { mark[q.digit[0] - '0'][q.digit[1] - '0'][q.digit[2] - '0'][q.digit[3] - '0'] = 1; Queue.push(q); } } } } } } int main() { int n; #ifndef ONLINE_JUDGE freopen("1195.txt", "r", stdin); #endif scanf("%d", &n); while (n--) { scanf("%s%s", a, b); if (strcmp(a, b) == 0) { printf("0/n"); } else { bfs(); } } return 0; }