UVa 10047 自行车 状态记录广搜

时间:2024-07-10 14:06:50

每个格子(x,y,drection,color)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char a[][];
int vis[][][][];
int n,m;
int dx[]={-,,,};
int dy[]={,,,-};
struct node{
int x,y,di,co,t;
node(int xx,int yy,int d,int c,int st)
{
x=xx;y=yy;di=d;co=c;t=st;
}
};
queue<node> q;
void bfs()
{
while(!q.empty())
{
node u=q.front();
q.pop();
if(a[u.x][u.y]=='T'&&u.co==)
{
printf("minimum time = %d sec\n",u.t);
return;
}
int x=u.x,y=u.y,co=u.co;
int di=(u.di+)%;//向右转
if(!vis[x][y][di][co])
{
vis[x][y][di][co]=;
q.push(node(x,y,di,co,u.t+));
}
di=(u.di+)%;//向左转
if(!vis[x][y][di][co])
{
vis[x][y][di][co]=;
q.push(node(x,y,di,co,u.t+));
}
di=u.di;//前进
x+=dx[di];y+=dy[di];
co=(co+)%;//下一种颜色
if(x<n&&x>=&&y<m&&y>=&&a[x][y]!='#'&&!vis[x][y][di][co])
{
q.push(node(x,y,di,co,u.t+));
vis[x][y][di][co]=;
}
}
printf("destination not reachable\n");
}
int main()
{
int ss=;
while(scanf("%d%d",&n,&m)&&n&&m)
{
if(ss>) printf("\n");
memset(vis,,sizeof(vis));
while(!q.empty()) q.pop();
for(int i=;i<n;i++)
for(int j=;j<m;j++)
{
cin>>a[i][j];
if(a[i][j]=='S')
{
q.push(node(i,j,,,));
vis[i][j][][]=;
}
}
printf("Case #%d\n",ss++);
bfs();
}
return ;
}