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 JAVA (judge verdict: Time Limit Exceeded)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//The Morning after Halloween
public class Main{

	int w, h, N, X = 16, Y = 256, YY = 256*256;
	int[][] d = {{-1,0},{0,1},{1,0},{0,-1},{0,0}};
	byte[][][] u;
	byte[][] u2;
	byte f2, f3;
	char[][] map;
	
	int one(){
		int si = 0, sj = 0, gi = 0, gj = 0;
		for(int i=0;i<h;i++)for(int j=0;j<w;j++){
			if(map[i][j]=='a'){
				map[i][j] = ' '; si = i; sj = j;
			}
			if(map[i][j]=='A'){
				map[i][j] = ' '; gi = i; gj = j;
			}
		}
		int[][] dist = new int[h][w];
		bfs(dist, gi, gj);
		return dist[si][sj];
	}
	
	int two(){
		int ai = 0, aj = 0, bi = 0, bj = 0, gai = 0, gaj = 0, gbi = 0, gbj = 0;
		for(int i=0;i<h;i++)for(int j=0;j<w;j++){
			if(map[i][j]=='a'){
				map[i][j] = ' '; ai = i; aj = j;
			}
			if(map[i][j]=='A'){
				map[i][j] = ' '; gai = i; gaj = j;
			}
			if(map[i][j]=='b'){
				map[i][j] = ' '; bi = i; bj = j;
			}
			if(map[i][j]=='B'){
				map[i][j] = ' '; gbi = i; gbj = j;
			}
		}
		int SA = ai*X+aj, SB = bi*X+bj, GA = gai*X+gaj, GB = gbi*X+gbj;
		u2[SA][SB] = f2;
		List<Integer> l = new ArrayList<Integer>();
		int res = 0;
		l.add(SA*Y+SB);
		while(!l.isEmpty()){
			List<Integer> next = new ArrayList<Integer>();
			for(int x:l){
				int A = x/Y, B = x%Y;
				if(A==GA&&B==GB){
					return res;
				}
				int pai = A/X, paj = A%X, pbi = B/X, pbj = B%X;
				for(int ka=0;ka<5;ka++)for(int kb=0;kb<5;kb++){
					int nai = pai+d[ka][0], naj = paj+d[ka][1], nbi = pbi+d[kb][0], nbj = pbj+d[kb][1];
					int NA = nai*X+naj, NB = nbi*X+nbj;
					if((NA==B&&NB==A)||NA==NB)continue;
					if(map[nai][naj]==' '&&map[nbi][nbj]==' '&&u2[NA][NB]!=f2){
						u2[NA][NB] = f2;
						next.add(NA*Y+NB);
					}
				}
			}
			res++;
			l = next;
		}
		return -1;
	}
	
	int three(){
		int ai = 0, aj = 0, bi = 0, bj = 0, ci = 0, cj = 0, gai = 0, gaj = 0, gbi = 0, gbj = 0, gci = 0, gcj = 0;
		for(int i=0;i<h;i++)for(int j=0;j<w;j++){
			if(map[i][j]=='a'){
				map[i][j] = ' '; ai = i; aj = j;
			}
			if(map[i][j]=='A'){
				map[i][j] = ' '; gai = i; gaj = j;
			}
			if(map[i][j]=='b'){
				map[i][j] = ' '; bi = i; bj = j;
			}
			if(map[i][j]=='B'){
				map[i][j] = ' '; gbi = i; gbj = j;
			}
			if(map[i][j]=='c'){
				map[i][j] = ' '; ci = i; cj = j;
			}
			if(map[i][j]=='C'){
				map[i][j] = ' '; gci = i; gcj = j;
			}
		}
		int SA = ai*X+aj, SB = bi*X+bj, SC = ci*X+cj, GA = gai*X+gaj, GB = gbi*X+gbj, GC = gci*X+gcj;
		u[SA][SB][SC] = f3;
		int[][] dA = new int[h][w], dB = new int[h][w], dC = new int[h][w];
		bfs(dA, gai, gaj); bfs(dB, gbi, gbj); bfs(dC, gci, gcj);
//		for(int i=0;i<h;i++){
//			for(int j=0;j<w;j++){
//				System.out.printf("%3d", dA[i][j]==1<<29?0:dA[i][j]);
//			}
//			System.out.println();
//		}
		int sda = dA[ai][aj], sdb = dB[bi][bj], sdc = dC[ci][cj];
		int max = Math.max(sda, Math.max(sdb, sdc));
		List<Integer> l = new ArrayList<Integer>();
		int res = 0;
		l.add(SA*YY+SB*Y+SC);
		while(!l.isEmpty()){
			List<Integer> next = new ArrayList<Integer>();
			for(int x:l){
				int A = x/YY, B = (x%YY)/Y, C = x%Y;
				if(A==GA&&B==GB&&C==GC){
					return res;
				}
				int pai = A/X, paj = A%X, pbi = B/X, pbj = B%X, pci = C/X, pcj = C%X;
				int da = dA[pai][paj], db = dB[pbi][pbj], dc = dC[pci][pcj];
				for(int ka=0;ka<5;ka++)for(int kb=0;kb<5;kb++)for(int kc=0;kc<5;kc++){
					int nai = pai+d[ka][0], naj = paj+d[ka][1], nbi = pbi+d[kb][0], nbj = pbj+d[kb][1], nci = pci+d[kc][0], ncj = pcj+d[kc][1];
					int NA = nai*X+naj, NB = nbi*X+nbj, NC = nci*X+ncj;
					if(NA==NC||NB==NC||NA==NB)continue;
					if((NA==B&&NB==A)||(NA==C&&NC==A)||(NB==C&&NC==B))continue;
					if(map[nai][naj]==' '&&map[nbi][nbj]==' '&&map[nci][ncj]==' '&&u[NA][NB][NC]!=f3){
						int DA = dA[nai][naj], DB = dB[nbi][nbj], DC = dC[nci][ncj];
						if(da<=DA&&db<=DB&&dc<=DC)continue;
						if(sda<=DA&&sdb<=DB&&sdc<=DC)continue;
						int MAX = Math.max(DA, Math.max(DB, DC));
						if(max+4<MAX)continue;
						if(59<res&&da+db+dc<=DA+DB+DC)continue;
						u[NA][NB][NC] = f3;
						next.add(NA*YY+NB*Y+NC);
					}
				}
			}
			res++;
			l = next;
		}
		return -1;
	}
	
	void bfs(int[][] dist, int si, int sj){
		for(int[]a:dist)Arrays.fill(a, 1<<29);
		dist[si][sj] = 0;
		List<int[]> l = new ArrayList<int[]>();
		l.add(new int[]{si, sj});
		int step = 1;
		while(!l.isEmpty()){
			List<int[]> next = new ArrayList<int[]>();
			for(int[]a:l){
				int pi = a[0], pj = a[1];
				for(int k=0;k<4;k++){
					int ni = pi+d[k][0], nj = pj+d[k][1];
					if(map[ni][nj]==' '&&step<dist[ni][nj]){
						dist[ni][nj] = step; next.add(new int[]{ni, nj});
					}
				}
			}
			l = next;
			step++;
		}
	}
	
	void run(){
		Scanner sc = new Scanner();
		u2 = new byte[256][256];
		u = new byte[256][256][256];
		f2 = f3 = 0;
		StringBuilder sb = new StringBuilder();
		for(;;){
			w = sc.nextInt(); h = sc.nextInt(); N = sc.nextInt();
			if((w|h|N)==0)break;
//			sc.nextLine();
//			long T = System.currentTimeMillis();
			f2++; f3++;
			map = new char[h][];
			for(int i=0;i<h;i++)map[i]=sc.nextLine().toCharArray();
			sb.append((N==1?one():N==2?two():three())+"\n");
//			System.out.println(System.currentTimeMillis()-T);
		}
		System.out.println(sb);
	}
	
	class Scanner {
		int nextInt() {
			try {
				int c = System.in.read();
				while (c != '-' && (c < '0' || '9' < c))
					c = System.in.read();
				if (c == '-') return -nextInt();
				int res = 0;
				do {
					res *= 10;
					res += c - '0';
					c = System.in.read();
				} while ('0' <= c && c <= '9');
				return res;
			} catch (Exception e) {
				return -1;
			}
		}
		String nextLine(){
			try{
				StringBuilder res =new StringBuilder("");
				int c = System.in.read();
				while (c=='\r' || c=='\n')
					c = System.in.read();
				do {
					res.append((char) c);
					c = System.in.read();
				} while (c!='\r' && c!='\n');
				return res.toString();
			}catch (Exception e) {
				return null;
			}
		}
	}
	
	public static void main(String[] args) {
		new Main().run();
	}
}