Problem:
Problem G: The Morning after Halloween

You are working for an amusement park as an operator of an obakeyashiki, or a haunted house,
in which guests walk through narrow and dark corridors. The house is proud of their lively
ghosts, which are actually robots remotely controlled by the operator, hiding here and there in
the corridors. One morning, you found that the ghosts are not in the positions where they are
supposed to be. Ah, yesterday was Halloween. Believe or not, paranormal spirits have moved
them around the corridors in the night. You have to move them into their right positions before
guests come. Your manager is eager to know how long it takes to restore the ghosts.

In this problem, you are asked to write a program that, given a floor map of a house, finds the
smallest number of steps to move all ghosts to the positions where they are supposed to be.

A floor consists of a matrix of square cells. A cell is either a wall cell where ghosts cannot move
into or a corridor cell where they can.

At each step, you can move any number of ghosts simultaneously. Every ghost can either stay
in the current cell, or move to one of the corridor cells in its 4-neighborhood (i.e. immediately
left, right, up or down), if the ghosts satisfy the following conditions:

No more than one ghost occupies one position at the end of the step.

No pair of ghosts exchange their positions one another in the step.

For example, suppose ghosts are located as shown in the following (partial) map, where a sharp sign ('#) represents a wall cell and 'a', 'b', and 'c' ghosts.

####
ab#
#c##
####

The following four maps show the only possible positions of the ghosts after one step.

#### #### #### ####
ab# a b# acb# ab #
#c## #c## # ## #c##
#### #### #### ####

Input

The input consists of at most 10 datasets, each of which represents a floor map of a house. The format of a dataset is as follows.

w h n
c11c12...c1w
c21c22...c2w
. . .. .
.. .
.
.. .
ch1ch2...chw

w, h and n in the first line are integers, separated by a space. w and h are the floor width
and height of the house, respectively. n is the number of ghosts. They satisfy the following constraints.

4 ≤ w ≤ 16

4 ≤ h ≤ 16

1 ≤ n ≤ 3

Subsequent h lines of w characters are the floor map. Each of cij is either:

a '#' representing a wall cell,

a lowercase letter representing a corridor cell which is the initial position of a ghost,

an uppercase letter representing a corridor cell which is the position where the ghost corresponding to its lowercase letter is supposed to be, or

a space representing a corridor cell that is none of the above.

In each map, each of the first n letters from a and the first n letters from A appears once and
only once. Outermost cells of a map are walls; i.e. all characters of the first and last lines are
sharps; and the first and last characters on each line are also sharps. All corridor cells in a
map are connected; i.e. given a corridor cell, you can reach any other corridor cell by following
corridor cells in the 4-neighborhoods. Similarly, all wall cells are connected. Any 2 × 2 area on
any map has at least one sharp. You can assume that every map has a sequence of moves of ghosts that restores all ghosts to the positions where they are supposed to be.

The last dataset is followed by a line containing three zeros separated by a space.

Output

For each dataset in the input, one line containing the smallest number of steps to restore ghosts
into the positions where they are supposed to be should be output. An output line should not
contain extra characters such as spaces.

Sample Input

5 5 2
#####
#A#B#
# #
#b#a#
#####
16 4 3
################
## ########## ##
# ABCcba #
################
16 16 3
################
### ## # ##
## # ## # c#
# ## ########b#
# ## # # # #
# # ## # # ##
## a# # # # #
### ## #### ## #
## # # # #
# ##### # ## ##
#### #B# # #
## C# # ###
# # # ####### #
# ###### A## #
# # ##
################
0 0 0

Output for the Sample Input

7
36
77

Solution in C++14 (judge verdict: Accepted)

#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<complex>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<utility>
#include<cassert>
using namespace std;

typedef long long  ll;

typedef unsigned long long ul;
typedef unsigned int ui;
const ll mod = 1000000007;
typedef double ld;
typedef complex<ld> Point;
const ll INF = mod * mod;
typedef pair<int, int> P;
#define stop char nyaa;cin>>nyaa;
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
const ld eps = 1e-8;
const ld pi = acos(-1.0);
typedef pair<ld, ld> LDP;
typedef pair<ll, ll> LP;
typedef vector<int> vec;

int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };

bool isalf(char t) {
	if ('a' <= t && t <= 'z')return true;
	return false;
}
bool isAlf(char t) {
	if ('A' <= t && t <= 'Z')return true;
	return false;
}

int h, w, n;
bool used[256][256][256];
char mp[16][16];
void solve() {
	int sx[3] = {}, sy[3] = {}, gx[3] = {}, gy[3] = {};
	string s; getline(cin, s);
	rep(i, h) {
		getline(cin, s);
		rep(j, w) {
			mp[i][j] = s[j];
			if (isalf(s[j])) {
				int z = s[j] - 'a';
				sx[z] = i, sy[z] = j;
			}
			else if (isAlf(s[j])) {
				int z = s[j] - 'A';
				gx[z] = i, gy[z] = j;
			}
		}
	}
	queue<vec> q;
	rep(i, h*w)rep(j, h*w)rep(k, h*w)used[i][j][k] = false;
	int cs[3];
	int cg[3];
	rep(i, 3)cs[i] = sx[i] * w + sy[i];
	rep(i, 3)cg[i] = gx[i] * w + gy[i];
	//rep(i, c)cout << cs[i] << endl;
	used[cs[0]][cs[1]][cs[2]] = true;
	q.push({ cs[0] , cs[1], cs[2] });
	int tmp = 0;
	while (!q.empty()) {
		int len = q.size();
		rep(aa, len) {
			vec v = q.front(); q.pop();
			if (v == vec{cg[0], cg[1], cg[2]}) {
				cout << tmp << endl; return;
			}
			int nx[3], ny[3],nz[3];
			rep(i, 9) {
				if (i % 2 == 0 && i != 4)continue;
				nx[0] = v[0] / w + i%3 - 1;
				ny[0] = v[0] % w + i/3 - 1;
				nz[0] = nx[0] * w + ny[0];
				if (mp[nx[0]][ny[0]] == '#')continue;
				if (n == 1) {
					if (used[nz[0]][0][0])continue;
					used[nz[0]][0][0] = true;
					q.push({ nz[0],0,0 });
					continue;
				}
				rep(j, 9) {
					if (j % 2 == 0 && j != 4)continue;
					nx[1] = v[1] / w + j % 3 - 1;
					ny[1] = v[1] % w + j / 3 - 1;
					nz[1] = nx[1] * w + ny[1];
					if (mp[nx[1]][ny[1]] == '#')continue;
					if (nz[0] == nz[1])continue;
					if (nz[0] == v[1] && v[0] == nz[1])continue;
					if (n == 2) {
						if (used[nz[0]][nz[1]][0])continue;
						used[nz[0]][nz[1]][0] = true;
						q.push({ nz[0],nz[1],0 });
						continue;
					}
					rep(k, 9) {
						if (k % 2 == 0 && k != 4)continue;
						nx[2] = v[2] / w + k % 3 - 1;
						ny[2] = v[2] % w + k / 3 - 1;
						nz[2] = nx[2] * w + ny[2];
						if (mp[nx[2]][ny[2]] == '#')continue;
							if (used[nz[0]][nz[1]][nz[2]])continue;
							if (nz[0] == nz[2]||nz[1]==nz[2])continue;
							if (nz[0] == v[2] && v[0] == nz[2])continue;
							if (nz[1] == v[2] && v[1] == nz[2])continue;
							used[nz[0]][nz[1]][nz[2]] = true;
							q.push({ nz[0],nz[1],nz[2] });
					}
				}
			}
		}
		tmp++;
	}

}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	//cout << fixed << setprecision(5);
	while (cin >> w>>h>>n,n)solve();
	//solve();
	//stop
	return 0;
}