1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include <iostream> #include <algorithm> #include <cstring> #include <cstdio> using std::min; using std::max; using std::swap; using std::memset; char mtr[6][6]; int sts[6][6]; int standard[6][6]= { {0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1}, {0, 0, 1, 1, 1, 1}, {0, 0, 0, 2, 1, 1}, {0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0} }; int dx[8] = {1, 1, -1, -1, 2, 2, -2, -2}; int dy[8] = {2, -2, 2, -2, 1, -1, 1, -1}; int ans, T, tagx, tagy, k; bool sol; bool jud(int matrix[6][6]) { for(int i = 1; i <= 5; ++i) for(int j = 1; j <= 5; ++j) { if(matrix[i][j] != standard[i][j]) return false; } return true; } bool g(int matrix[6][6], int now) { int val = 0; for(int i = 1; i <= 5; ++i) for(int j = 1; j <= 5; ++j) { if(matrix[i][j] != standard[i][j]) { val++; if(val + now > k) return false; } } return true; } void A_star(int st, int matrix[6][6], int x, int y) { if(st == k) {if(jud(matrix)) sol = true; return;} if(sol) return; for(int i = 0; i < 8; ++i) { int nx = x + dx[i], ny = y + dy[i]; if(nx < 1 || nx > 5 || ny < 1 || ny > 5) continue; swap(matrix[x][y], matrix[nx][ny]); if(g(matrix, st)) A_star(st + 1, matrix, nx, ny); swap(matrix[x][y], matrix[nx][ny]); } } int main() { scanf("%d", &T); while(T--) { sol = false; memset(sts, 0, sizeof sts); for(int i = 1; i <= 5; ++i) { scanf("%s", mtr[i] + 1); for(int j = 1; j <= 5; ++j) { if(mtr[i][j] == '*') sts[i][j] = 2, tagx = i, tagy = j; else if(mtr[i][j] == '0') sts[i][j] = 0; else sts[i][j] = 1; } } for(k = 1; k <= 15; ++k) { A_star(0, sts, tagx, tagy); if(sol){ printf("%d\n", k); break; } } if(!sol) puts("-1"); } return 0; }
|