111

· · 个人记录

#include<bits/stdc++.h>
using namespace std;
struct state
{
    int x,y,dir,color,time;
};
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
char grid[100][100];
bool visited[100][100][5][5];
int n,m;
int sx,sy,ex,ey;
int bfs()
{
    queue<state> q;
    q.push({sx,sy,0,0,0});
    visited[sx][sy][0][0]=true;
    while(!q.empty())
    {
        state s=q.front();
        q.pop();
        if(s.x==ex&&s.y==ey&&s.color==0)
        {
            return s.time;
        }
        int nx=s.x+dx[s.dir],ny=s.y+dy[s.dir];
        if(nx>=0&&nx<m&&ny>=0&&ny<n&&grid[nx][ny]!='#')
        {
            int nc=(s.color+1)%5;
            if(!visited[nx][ny][s.dir][nc])
            {
                visited[nx][ny][s.dir][nc]=true;
                q.push({nx,ny,s.dir,nc,s.time+1});
            }
        }
        int nd=(s.dir+3)%4;
        if(!visited[s.x][s.y][nd][s.color])
        {
            visited[s.x][s.y][nd][s.color]=true;
            q.push({s.x,s.y,nd,s.color,s.time+1});
        }
        nd=(s.dir+1)%4;
        if(!visited[s.x][s.y][nd][s.color])
        {
            visited[s.x][s.y][nd][s.color]=true;
            q.push({s.x,s.y,nd,s.color,s.time+1});
        }
    }
    return -1;
}
int main()
{
    cin>>m>>n;
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            cin>>grid[i][j];
            if(grid[i][j]=='S')
            {
                sx=i;
                sy=j;
            }
            if(grid[i][j]=='T')
            {
                ex=i;
                ey=j;
            }
        }
    }
    int ans=bfs();
    if(ans==-1)
    {
        cout<<"";
    }
    else
    {
        cout<<ans;
    }
    return 0;
}