// by BNU_LZM
#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
char map[20][20];
int s[4], t[4], d[300][300][300];
int dx[] = {0, 0, 0, 1, -1};
int dy[] = {0, 1, -1, 0, 0};
vector<int> a[300];
int ID(int x, int y, int z)
{
return (x<<16) | (y<<8) | z;
}
bool pd(int x, int nx, int y, int ny)
{
if((x == ny && y == nx) || (nx == ny)) return true;
else return false;
}
int bfs()
{
queue<int> q;
q.push(ID(s[0], s[1], s[2]));
memset(d, -1, sizeof(d));
d[s[0]][s[1]][s[2]] = 0;
while(!q.empty())
{
int u = q.front(); q.pop();
int x = (u>>16) & 0xff, y = (u>>8) & 0xff, z = u & 0xff;
if(x == t[0] && y == t[1] && z == t[2]) return d[x][y][z];
for(int i = 0; i < a[x].size(); i++)
{
int nx = a[x][i];
for(int j = 0; j < a[y].size(); j++)
{
int ny = a[y][j];
if(pd(x, nx, y, ny)) continue;
for(int k = 0; k < a[z].size(); k++)
{
int nz = a[z][k];
if(pd(x, nx, z, nz)) continue;
if(pd(y, ny, z, nz)) continue;
if(d[nx][ny][nz] > -1) continue;
d[nx][ny][nz] = d[x][y][z]+1;
q,push(ID(nx, ny, nz));
}
}
}
}
return -1;
}
int main()
{
int h, w, n;
int x[300], y[300], id[20][20];
scanf("%d%d%d", &h, &w, &n);
for(int i = 0; i < h; i++)
fgets(map[i], 20, stdin);
int cnt = 0;
for(int i = 0; i < h; i++)
for(int j = 0; j < w; j++)
{
if(map[i][j] != '#')
{
x[cnt] = i; y[cnt] = j;
if(islower(map[i][j]))
{
s[map[i][j]-'a'] = cnt;
}
if(isupper(map[i][j]))
{
t[map[i][j]-'A'] = cnt;
}
id[i][j] = cnt;
cnt++;
}
}
for(int i = 0; i < cnt; i++)
{
for(int j = 0; j < 5; j++)
{
int nx = x[i]+dx[j], ny = y[i]+dy[j];
if(nx < 0 || nx >= w || ny < 0 || ny >= h) continue;
if(map[nx][ny] != '#')
{
a[i].push_back(id[nx][ny]);
}
}
}
if(n <= 2) { s[2] = t[2] = cnt; a[cnt].push_back(cnt); cnt++; }
if(n <= 1) { s[1] = t[1] = cnt; a[cnt].push_back(cnt); cnt++; }
printf("%d\n", bfs());
return 0;
}
万圣节后的早晨
最新推荐文章于 2021-03-28 09:10:12 发布