独轮车

· · 个人记录

#include<bits/stdc
```cpp
#include<bits/stdc++.h>
using namespace std;
int n,m,sx,sy;
struct qwq
{
    int x,y,d,c,t;
};
queue<qwq> q;
bool vis[30][30][4][5];
int dx[5]={-1,0,1,0};
int dy[5]={0,1,0,-1};
int a[100][100];
int bfs()
{
    q.push({sx,sy,0,0,0});
    vis[sx][sy][0][0]=1;
    while(!q.empty())
    {
        qwq s=q.front();
        q.pop();
        if(a[s.x][s.y]==2&&s.c==0)
        {
            return s.t;
        }
        int nx=s.x+dx[s.d],ny=s.y+dy[s.d];
        if(nx>=0&&nx<m&&ny>=0&&ny<n&&a[nx][ny]!=1)
        {
            int nc=(s.c+1)%5;
            if(!vis[nx][ny][s.d][nc])
            {
                vis[nx][ny][s.d][nc]=1;
                q.push({nx,ny,s.d,nc,s.t+1});
            }
        }
        int nd=(s.d+3)%4;
        if(!vis[s.x][s.y][nd][s.c])
        {
            vis[s.x][s.y][nd][s.c]=1;
            q.push({s.x,s.y,nd,s.c,s.t+1});
        }
        nd=(s.d+1)%4;
        if(!vis[s.x][s.y][nd][s.c])
        {
            vis[s.x][s.y][nd][s.c]=1;
            q.push({s.x,s.y,nd,s.c,s.t+1});
        }
    }
    return -1;
}
int main()
{

    char z;
    cin>>n>>m;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            cin>>z;
            if(z=='#')
            {
                a[i][j]=1;
            }
            if(z=='S')
            {
                sx=i;
                sy=j;
            }
            if(z=='T')
            {
                a[i][j]=2;
            }
        }
    }
    int ans=bfs();
    if(ans==-1)
    {
        cout<<-1;
    }
    else
    {
        cout<<ans;
    }

    return 0;
}

++.h> using namespace std; int n,m,sx,sy,ex,ey; bool vis[30][30][4][5]; int dx[]={-1,0,1,0}; int dy[]={0,1,0,-1}; char a[1100][1100]; struct Node { int x,y,dir,co,ti; }; int bfs() {
queue<Node> q; q.push({sx,sy,0,0,0}); vis[sx][sy][0][0]=true; while(!q.empty()) { Node s=q.front(); q.pop(); if(s.x==ex&&s.y==ey&&s.co==0) return s.ti; int nx=s.x+dx[s.dir],ny=s.y+dy[s.dir]; if(nx>=0&&nx<n&&ny>=0&&ny<m&&a[nx][ny]!='#') { int nc=(s.co+1)%5; if(!vis[nx][ny][s.dir][nc]) { vis[nx][ny][s.dir][nc]=true; q.push({nx,ny,s.dir,nc,s.ti+1}); } } int nd=(s.dir+3)%4; if(!vis[s.x][s.y][nd][s.co]) { vis[s.x][s.y][nd][s.co]=true; q.push({s.x,s.y,nd,s.co,s.ti+1}); } nd=(s.dir+1)%4; if(!vis[s.x][s.y][nd][s.co]) { vis[s.x][s.y][nd][s.co]=true; q.push({s.x,s.y,nd,s.co,s.ti+1}); } } return -1; } int main() { cin>>n>>m; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { cin>>a[i][j]; if(a[i][j]=='S') { sx=i,sy=j; } if(a[i][j]=='T') { ex=i,ey=j; } } } int ans=bfs(); if(ans==-1) cout<<"destination not reachable"; else cout<<ans<<'\n'; return 0; }