#include #include #include #include #include using namespace std; int w, h, n; char field[17][17]; static int dx[5] = {0, -1, 0, 1, 0}; static int dy[5] = {0, 0, 1, 0, -1}; #define ENCODE(ax,ay,bx,by,cx,cy) (((ax)<<0)|((ay)<<4)|((bx)<<8)|((by)<<12)|((cx)<<16)|((cy)<<20)) int main() { while (cin >> w >> h >> n) { if (w == 0 && h == 0 && n == 0) { break; } cin.ignore(w+1, '\n'); int start_state = 0x000000, goal_state = 0x000000; for (int i = 0; i < h; ++i) { cin.get(field[i], w+1, '\n'); cin.ignore(w+1, '\n'); for (int j = 0; j < w; ++j) { if (field[i][j] == 'a') { start_state |= (j << 0) | (i << 4); } if (field[i][j] == 'b') { start_state |= (j << 8) | (i << 12); } if (field[i][j] == 'c') { start_state |= (j << 16) | (i << 20); } if (field[i][j] == 'A') { goal_state |= (j << 0) | (i << 4); } if (field[i][j] == 'B') { goal_state |= (j << 8) | (i << 12); } if (field[i][j] == 'C') { goal_state |= (j << 16) | (i << 20); } } } queue< pair > current_states; set visited_states; current_states.push(make_pair(start_state, 1)); visited_states.insert(start_state); while (!current_states.empty()) { pair p = current_states.front(); current_states.pop(); int steps = p.second; int ax = (p.first & 0x00000F) >> 0; int ay = (p.first & 0x0000F0) >> 4; int bx = (p.first & 0x000F00) >> 8; int by = (p.first & 0x00F000) >> 12; int cx = (p.first & 0x0F0000) >> 16; int cy = (p.first & 0xF00000) >> 20; for (int ai = 0; ai < 5; ++ai) { int nax = ax + dx[ai], nay = ay + dy[ai]; if (nax < 0 || nax >= w || nay < 0 || nay >= h || field[nay][nax] == '#') { continue; } for (int bi = 0; bi < (n >= 2 ? 5 : 1); ++bi) { int nbx = bx + dx[bi], nby = by + dy[bi]; if (nbx < 0 || nbx >= w || nby < 0 || nby >= h || (n >= 2 && field[nby][nbx] == '#')) { continue; } if (n >= 2 && nax == nbx && nay == nby) { continue; } if (n >= 2 && nax == bx && nay == by && nbx == ax && nby == ay) { continue; } for (int ci = 0; ci < (n >= 3 ? 5 : 1); ++ci) { int ncx = cx + dx[ci], ncy = cy + dy[ci]; if (ncx < 0 || ncx >= w || ncy < 0 || ncy >= h || (n >= 3 && field[ncy][ncx] == '#')) { continue; } if (n >= 3 && nax == ncx && nay == ncy) { continue; } if (n >= 3 && nbx == ncx && nby == ncy) { continue; } if (n >= 3 && nax == cx && nay == cy && ncx == ax && ncy == ay) { continue; } if (n >= 3 && ncx == bx && ncy == by && nbx == cx && nby == cy) { continue; } int new_state = ENCODE(nax, nay, nbx, nby, ncx, ncy); if (new_state == goal_state) { cout << steps << endl; goto found; } if (visited_states.find(new_state) == visited_states.end()) { current_states.push(make_pair(new_state, steps+1)); visited_states.insert(new_state); } } } } } found: ; } return 0; }