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
| #include <iostream> #include <cstdio> #include <cstring> using namespace std; int Map[6][6]; const int goal[5][5] = {{2, 2, 2, 2, 2}, {1, 2, 2, 2, 2}, {1, 1, 0, 2, 2}, {1, 1, 1, 1, 2}, {1, 1, 1, 1, 1}}; const int fx[9] = {1, 1, -1, -1, 2, 2, -2, -2}, fy[9] = {2, -2, 2, -2, 1, -1, 1, -1}; bool flag; int ans; bool inside(int x, int y) { return x > 0 && y > 0 && x <= 5 && y <= 5; } int cost() { int res = 0; for (int i = 1; i <= 5; i++) for (int j = 1; j <= 5; j++) res += (Map[i][j] != goal[i - 1][j - 1]); return res; } void dfs(int x, int y, int s, int limit) { if (flag) return; if (s >= limit) { if (!cost()) { ans = s; flag = true; } return; } for (int i = 0; i < 8; i++) { int nx = x + fx[i], ny = y + fy[i]; if (!inside(nx, ny)) continue; swap(Map[x][y], Map[nx][ny]); if (cost() + s <= limit) dfs(nx, ny, s + 1, limit); swap(Map[x][y], Map[nx][ny]); } } int main() { int T; cin >> T; while (T--) { ans = 0; flag = false; int sx, sy; for (int i = 1; i <= 5; i++) for (int j = 1; j <= 5; j++) { char c; cin >> c; if (c == '*') { sx = i; sy = j; Map[i][j] = 0; } else Map[i][j] = c - '0' + 1; } if (!cost()) { puts("0"); continue; } for (int i = 1; i <= 15; i++) dfs(sx, sy, 0, i); if (flag) cout << ans << endl; else cout << -1 << endl; } return 0; }
|