此题涉及颜色跟方向,标记数组可以开城四维分别表示坐标,方向和颜色。刚开始思路比较乱,做完之后要三思啊。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=30;
struct node
{
int x,y;
int drection;
int color;
int time;
};
char grid[maxn][maxn];
int dx[]= {-1,0,1,0};
int dy[]= {0,1,0,-1};
int vis[maxn][maxn][5][5];
int N,M;
int sx,sy,ex,ey;
string Color[]= {"green","black","red","blue","white"};
bool BFS()
{
queue<node> q;
node a,b;
a.x=sx,a.y=sy,a.drection=0,a.color=0;
a.time=0;
q.push(a);
while(!q.empty())
{
a=q.front();
q.pop();
if(a.x==ex&&a.y==ey&&a.color==0)
{
printf("minimum time = %d sec\n",a.time);
return true;
}
b.time=a.time+1;
b.x=a.x+dx[a.drection],b.y=a.y+dy[a.drection];
b.drection=a.drection;
b.color=(a.color+1)%5;
if(b.x>=1&&b.x<=N&&b.y>=1&&b.y<=M&&grid[b.x][b.y]!='#'&&!vis[b.x][b.y][b.drection][b.color])
{
q.push(b);
vis[b.x][b.y][b.drection][b.color]=1;
}
b.x=a.x,b.y=a.y;
b.drection=(a.drection+3)%4;
b.color=a.color;
if(!vis[b.x][b.y][b.drection][b.color])
{
q.push(b);
vis[b.x][b.y][b.drection][b.color]=1;
}
b.drection=(a.drection+1)%4;
if(!vis[b.x][b.y][b.drection][b.color])
{
q.push(b);
vis[b.x][b.y][b.drection][b.color]=1;
}
}
return false;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int cas=1;
while(cin>>N>>M,N+M)
{
if(cas!=1)printf("\n");
for(int i=1; i<=N; i++)
{
for(int j=1; j<=M; j++)
{
cin>>grid[i][j];
if(grid[i][j]=='S')
{
sx=i,sy=j;
}
if(grid[i][j]=='T')
{
ex=i,ey=j;
}
}
}
memset(vis,0,sizeof(vis));
vis[sx][sy][0][0]=1;
printf("Case #%d\n",cas++);
if(!BFS())cout<<"destination not reachable"<<endl;
}
return 0;
}