链接
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=988
题解
这题交了5发才过,而且做了一个小时确实是有点不甘心…赛场上可能会被队友怼QwQ
四个参数{行,列,方向,颜色}
搞一个queue<vector<int>>就比较好写了
代码
#include <bits/stdc++.h>
#define iinf 0x3f3f3f3f
using namespace std;
#define maxn 30
bool vis[maxn][maxn][4][5];
int dis[maxn][maxn][4][5], Sx, Sy, Tx, Ty, dx[]{-1,0,1,0}, dy[]{0,1,0,-1}, N, M;
char mp[maxn][maxn];
bool judge(int x, int y)
{
if(x<1 or x>M)return false;
if(y<1 or y>N)return false;
return mp[x][y]!='#';
}
int bfs()
{
queue<vector<int>> q;
memset(vis,0,sizeof(vis));
memset(dis,0x3f,sizeof(dis));
dis[Sx][Sy][0][0]=0;
vis[Sx][Sy][0][0]=true;
q.emplace(vector<int>{Sx,Sy,0,0});
while(!q.empty())
{
auto now=q.front(); q.pop();
if(!vis[now.at(0)][now.at(1)][now.at(2)+1&3][now.at(3)])
{
dis[now.at(0)][now.at(1)][now.at(2)+1&3][now.at(3)]=dis[now.at(0)][now.at(1)][now.at(2)][now.at(3)]+1;
vis[now.at(0)][now.at(1)][now.at(2)+1&3][now.at(3)]=true;
auto to=now; to[2]=to[2]+1&3;
q.emplace(to);
}
if(!vis[now.at(0)][now.at(1)][now.at(2)-1&3][now.at(3)])
{
dis[now.at(0)][now.at(1)][now.at(2)-1&3][now.at(3)]=dis[now.at(0)][now.at(1)][now.at(2)][now.at(3)]+1;
vis[now.at(0)][now.at(1)][now.at(2)-1&3][now.at(3)]=true;
auto to=now; to[2]=to[2]-1&3;
q.emplace(to);
}
auto to=now;
to[0]+=dx[now.at(2)], to[1]+=dy[now.at(2)], to[3]=(to[3]+1)%5;
if(judge(to.at(0),to.at(1)) and !vis[to.at(0)][to.at(1)][to.at(2)][to.at(3)])
{
dis[to.at(0)][to.at(1)][to.at(2)][to.at(3)]=dis[now.at(0)][now.at(1)][now.at(2)][now.at(3)]+1;
vis[to.at(0)][to.at(1)][to.at(2)][to.at(3)]=true;
q.emplace(to);
}
}
int ans(iinf);
for(auto i=0;i<4;i++)ans=min(ans,dis[Tx][Ty][i][0]);
return ans;
}
int main()
{
ios::sync_with_stdio(false);
int kase(0);
while(cin>>M>>N, (N|M) )
{
for(auto i=1;i<=M;i++)cin>>mp[i]+1;
for(auto i=1;i<=M;i++)for(auto j=1;j<=N;j++)
if(mp[i][j]=='S')Sx=i, Sy=j;
else if(mp[i][j]=='T')Tx=i, Ty=j;
auto ans=bfs();
if(kase)cout<<endl;
cout<<"Case #"<<++kase<<endl;
if(ans==iinf)cout<<"destination not reachable\n";
else cout<<"minimum time = "<<ans<<" sec"<<endl;
}
return 0;
}