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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdio> #include <queue> #include <cstring> using namespace std;
int w, h, n, s[3], t[3]; char dataset[20][20]; int G[200][5], vis[200][200][200], dist[200][200][200]; int deg[200];
int dx[] = { 0,-1,1,0,0 }; int dy[] = { 0,0,0,-1,1 };
inline int ID(int a, int b, int c) { return(a << 16) | (b << 8) | c; } inline bool conflict(int a, int b, int a2, int b2) { return((a2 == b2) || (a == b2 && b == a2)); } int bfs() { queue<int>q; q.push(ID(s[0], s[1], s[2])); dist[s[0]][s[1]][s[2]] = 0; while (!q.empty()) { int u = q.front(); q.pop(); int a = (u >> 16) & 0xff; int b = (u >> 8) & 0xff; int c = u & 0xff; if (a == t[0] && b == t[1] && c == t[2]) return dist[a][b][c]; for (int i = 0; i < deg[a]; i++) { int a2 = G[a][i]; for (int j = 0; j < deg[b]; j++) { int b2 = G[b][j]; if (conflict(a, b, a2, b2)) continue; for (int k = 0; k < deg[c]; k++) { int c2 = G[c][k]; if (conflict(a, c, a2, c2) || conflict(b, c, b2, c2)) continue; if (dist[a2][b2][c2] == -1) { dist[a2][b2][c2] = dist[a][b][c] + 1; q.push(ID(a2, b2, c2)); } } } } } return -1; } int main() { while (~scanf("%d%d%d\n", &w, &h, &n) && n) { for (int i = 0; i < h; i++) fgets(dataset[i], 20, stdin); int cnt = 0, x[200], y[200], id[20][20]; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (dataset[i][j] != '#') { x[cnt] = i; y[cnt] = j; id[i][j] = cnt; if (islower(dataset[i][j])) s[dataset[i][j] - 'a'] = cnt; else if (isupper(dataset[i][j])) t[dataset[i][j] - 'A'] = cnt; cnt++; } } } for (int i = 0; i < cnt; i++) { deg[i] = 0; for (int j = 0; j < 5; j++) { int nx = x[i] + dx[j]; int ny = y[i] + dy[j]; if (dataset[nx][ny] != '#') G[i][deg[i]++] = id[nx][ny]; } } if (n <= 2) { deg[cnt] = 1; G[cnt][0] = cnt; s[2] = t[2] = cnt++; } if (n <= 1) { deg[cnt] = 1; G[cnt][0] = cnt; s[1] = t[1] = cnt++; } memset(dist, -1, sizeof(dist)); printf("%d\n", bfs()); } return 0; }
|