题目:https://vjudge.net/problem/UVA-1601
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<vector>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<queue>
#pragma warning(disable:4996)
using namespace std;
const int maxs = 20;
const int maxn = 150;
const int dx[] = { 0,0,-1,1,0 };
const int dy[] = { 1,-1,0,0,0 };
inline int ID(int a, int b, int c) {
return (a << 16) | (b << 8) | c;
}
int s[3], t[3];
int deg[maxn], G[maxn][5];
inline bool ok(int a, int b, int a1, int b1)
{
return a == b || (a1 == b && b1 == a);
}
int d[maxn][maxn][maxn];
int bfs()
{
queue <int>q;
memset(d, -1, sizeof(d));
q.push(ID(s[0], s[1], s[2]));
d[s[0]][s[1]][s[2]] = 0;
while (!q.empty())
{
int n = q.front(); q.pop();
int a = (n >> 16) & 0xff, b = (n >> 8) & 0xff, c = n & 0xff;
if (a == t[0] && b == t[1] && c == t[2])return d[a][b][c];
for (int i = 0; i < deg[a]; i++)
{
int na = G[a][i];
for (int j = 0; j < deg[b]; j++)
{
int nb = G[b][j];
if (ok(a, b, na, nb))continue;
for (int k = 0; k < deg[c]; k++)
{
int nc = G[c][k];
if (ok(a, c, na, nc))continue;
if (ok(b, c, nb, nc))continue;
if (d[na][nb][nc] != -1)continue;
d[na][nb][nc] = d[a][b][c] + 1;
q.push(ID(na, nb, nc));
}
}
}
}
return -1;
}
int main()
{
int h, w, n;
while (scanf("%d%d%d\n", &w, &h, &n) == 3 && n)
{
char maze[20][20];
for (int i = 0; i < h; i++)
fgets(maze[i], 20, stdin);
int cnt = 0, x[maxn], y[maxn], id[maxs][maxs];
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
if (maze[i][j] != '#')
{
x[cnt] = i; y[cnt] = j;
id[i][j] = cnt;
if (islower(maze[i][j])) s[maze[i][j] - 'a'] = cnt;
else if (isupper(maze[i][j])) t[maze[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], ny = y[i] + dy[j];
if (maze[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++; }
printf("%d\n", bfs());
}
return 0;
}