沒什麼好說的 BFS模板題 只不過把傳統的二維數組變成四維數組
AC代碼:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
#define maxn 20
#define inf 0x3f3f3f3f
int a[maxn][maxn][maxn][maxn];
int vis[maxn][maxn][maxn][maxn];
char m[maxn][maxn];
int mini;
int g[4][4]= { 0, 1, 0,-1,
0,-1, 0, 1,
1, 0, 1, 0,
-1, 0, -1, 0,
};
struct point
{
int xl;
int yl;
int xr;
int yr;
} s;
queue<point>q;
bool judge(point tmp)
{
if(tmp.xl>=10||tmp.xl<0||tmp.yl>=15||tmp.yl<0)
return false;
if(tmp.xr>=10||tmp.xr<0||tmp.yr>=15||tmp.yr<0)
return false;
if(m[tmp.xl][tmp.yl]=='#'&&m[tmp.xr][tmp.yr]=='#')
return false;
if(vis[tmp.xl][tmp.yl][tmp.xr][tmp.yr]==1)
return false;
return true;
}
void bfs()
{
q.push(s);
while(!q.empty())
{
point v=q.front();
q.pop();
for(int i=0; i<4; i++)
{
point tmp;
tmp.xl=v.xl+g[i][0];
tmp.yl=v.yl+g[i][1];
if(m[tmp.xl][tmp.yl]=='#'||tmp.xl>=10||tmp.xl<0||tmp.yl<0||tmp.yl>=15)
{
tmp.xl=v.xl;
tmp.yl=v.yl;
}
tmp.xr=v.xr+g[i][2];
tmp.yr=v.yr+g[i][3];
if(m[tmp.xr][tmp.yr]=='#'||tmp.xr>=10||tmp.xr<0||tmp.yr<0||tmp.yr>=15)
{
tmp.xr=v.xr;
tmp.yr=v.yr;
}
if(judge(tmp))
{
q.push(tmp);
vis[tmp.xl][tmp.yl][tmp.xr][tmp.yr]=1;
a[tmp.xl][tmp.yl][tmp.xr][tmp.yr]=a[v.xl][v.yl][v.xr][v.yr]+1;
}
}
}
}
int main()
{
int kase=0;
while(scanf("%s",m[0])!=EOF)
{
kase++;
while(!q.empty()) q.pop();
int ex,ey;
mini=inf;
for(int i=1; i<10; i++)
{
scanf("%s",m[i]);
}
memset(a,-1,sizeof(a));
memset(vis,0,sizeof(vis));
for(int i=0; i<10; i++)
{
for(int j=0; j<15; j++)
{
if(m[i][j]=='C')
{
ex=i;
ey=j;
}
if(m[i][j]=='M')
{
s.xl=i;
s.yl=j;
}
else if(m[i][j]=='G')
{
s.xr=i;
s.yr=j;
}
}
}
vis[s.xl][s.yl][s.xr][s.yr]=1;
a[s.xl][s.yl][s.xr][s.yr]=0;
bfs();
if(a[ex][ey-1][ex][ey+1]>0)
{
mini=min(a[ex][ey-1][ex][ey+1],mini);
}
if(a[ex][ey+1][ex][ey-1]>0)
{
mini=min(a[ex][ey+1][ex][ey-1],mini);
}
if(mini!=inf) printf("Case %d: %d\n",kase,mini);
else printf("Case %d: They can't break open the cage!\n",kase);
}
}