TOJ 2470 -- Robot in Maze

BFS,开始没看题结果样例都过不去,后来看了题发现是要考虑转向的步数,加一个判断就可以了。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
#include <queue>
#include <set>

using namespace std;

int dirx[]={0,0,1,-1};

int diry[]={1,-1,0,0};

int n,m,sx,sy,ex,ey;

bool vis[105][105][5];

char mp[105][105];

struct point
{
    int x,y,step,dir;
    friend bool operator < (const point& a,const point& b)
    {
        return a.step>b.step;
    }
};

bool judge(int x,int y,int i)
{
    return (x>=0&&x<n&&y>=0&&y<m&&!vis[x][y][i]&&mp[x][y]!='#');
}

int fuck(int x,int y)
{
    if(x==0)
    {
        if(y==0)return 0;
        if(y==1)return 2;
        if(y==2)return 1;
        if(y==3)return 1;
    }if(x==1)
    {
        if(y==0)return 2;
        if(y==1)return 0;
        if(y==2)return 1;
        if(y==3)return 1;
    }if(x==2)
    {
        if(y==0)return 1;
        if(y==1)return 1;
        if(y==2)return 0;
        if(y==3)return 2;
    }if(x==3)
    {
        if(y==0)return 1;
        if(y==1)return 1;
        if(y==2)return 2;
        if(y==3)return 0;
    }
}

int bfs()
{
    priority_queue <point> q;
    point F,N;
    F.x=sx;F.y=sy;
    F.step=0;F.dir=3;
    q.push(F);
    vis[sx][sy][3]=true;
    while(!q.empty())
    {
        F=q.top();q.pop();
        if(F.x==ex&&F.y==ey)return F.step;
        for(int i=0;i<4;++i)
        {
            N.x=F.x+dirx[i];
            N.y=F.y+diry[i];
            if(judge(N.x,N.y,i))
            {
                N.step=F.step+fuck(F.dir,i)+1;
                N.dir=i;
                q.push(N);
                vis[N.x][N.y][i]=true;
            }
        }
    }
    return -1;
}

int main()
{
    //freopen("in.txt", "r", stdin);
    int T;scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0;i<n;++i)
        {
            scanf("%s",&mp[i]);
            for(int j=0;j<m;++j)
            {
                if(mp[i][j]=='S')
                {
                    sx=i;sy=j;
                }
                else if(mp[i][j]=='T')
                {
                    ex=i;ey=j;
                }
            }
        }
        memset(vis,false,sizeof(vis));
        printf("%d\n",bfs());
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值