由于条件中有一条“每2*2的区间内至少有一个#”,所以空地的个数比较有限。于是就想到将空地离散成点,这样就可以比较高效地进行bfs了(主要还是储存,如果不离散的话储存和判重会很恶心)。
本题也可以使用双向bfs进行优化,不过既然给了12s的限时,那就没有这个必要了。
还有题目给的人数是1~3不等,如果要分开算的话会比较麻烦,将不存在的人放在一个起点和终点相同的地方一起参与bfs,就可以省很多事情。
#include<iostream>
#include<string>
#include<cstdio>
#include<set>
#include<stack>
#include<list>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<fstream>
using namespace std;
typedef long long ll;
const int xx[] = {0,0,0,-1,1};
const int yy[] = {0,-1,1,0,0};
const int maxn = 17,maxe = 200;
int n,m,c,cnt;
pair<int,int> st[3],ed[3];
char a[maxn][maxn];
pair<int,int> emp[maxe];
int Rank[maxn][maxn];
int vis[maxe][maxe][maxe];
int getID(int x,int y){//给空地重新标记
if (Rank[x][y]) return Rank[x][y];
else{
emp[++cnt] = {x,y};
return Rank[x][y] = cnt;
}
}
struct node{
int x,y,z;
};
bool canmove(int d,int pla){//判断是否能够移动到目标点
int x = emp[pla].first,y = emp[pla].second;
int nx = x + xx[d],ny = y + yy[d];
if (nx < 0 && ny < 0){
return d == 0;
}
if (nx < 0 || nx >= n || ny < 0 || ny >= m || a[nx][ny] == '#') return false;
return true;
}
int move(int d,int pla){
int x = emp[pla].first,y = emp[pla].second;
int nx = x + xx[d],ny = y + yy[d];
return getID(nx, ny);
}
bool check(int x,int nx,int y,int ny,int z,int nz){//判断行动是否合法
if (nx == ny || nx == nz || ny == nz) return false;
if (nx == y && ny == x) return false;
if (nx == z && nz == x) return false;
if (nz == y && ny == z) return false;
return true;
}
int bfs(){
queue<node> q;
int sx = getID(st[0].first,st[0].second);
int sy = getID(st[1].first,st[1].second);
int sz = getID(st[2].first,st[2].second);
int ex = getID(ed[0].first,ed[0].second);
int ey = getID(ed[1].first,ed[1].second);
int ez = getID(ed[2].first,ed[2].second);
q.push({sx,sy,sz});
vis[sx][sy][sz] = 1;
while (!q.empty()){
node now = q.front();q.pop();
for(int i = 0;i < 5;++i){
if (!canmove(i,now.x)) continue;
int nx = move(i,now.x);
for(int j = 0;j < 5;++j){
if (!canmove(j,now.y)) continue;
int ny = move(j,now.y);
for(int k = 0;k < 5;++k){
if (!canmove(k,now.z)) continue;
int nz = move(k,now.z);
if (!check(now.x,nx,now.y,ny,now.z,nz)) continue;
if (vis[nx][ny][nz]) continue;
vis[nx][ny][nz] = vis[now.x][now.y][now.z] + 1;
if (nx == ex && ny == ey && nz == ez){
return vis[nx][ny][nz] - 1;
}
q.push({nx,ny,nz});
}
}
}
}
return -1;
}
void init(){
cnt = 0;
memset(Rank,0,sizeof Rank);
memset(emp,0,sizeof emp);
for(int i = 0;i < 3;++i){
st[i] = ed[i] = {-i,-i};//如果有点不存在,那么它将被放置在一个不存在的位置中,起点和终点相同
}
getchar();
for(int i = 0;i < n;++i){
for(int j = 0;j < m;++j)
{
a[i][j] = getchar();
if (a[i][j] != '#') getID(i,j);
switch(a[i][j]){
case 'a':st[0] = {i,j};break;
case 'b':st[1] = {i,j};break;
case 'c':st[2] = {i,j};break;
case 'A':ed[0] = {i,j};break;
case 'B':ed[1] = {i,j};break;
case 'C':ed[2] = {i,j};break;
}
}
getchar();
}
memset(vis,0,sizeof vis);
int p = bfs();
if (p != -1) cout << p << endl;
else cout << "404 Not Found!" << endl;
}
int main(){
while(cin >> m >> n >> c && n + m + c){
init();
}
}