Patrol Robot

点击打开链接

题意:有一个n行m列的网格,机器人要从(0,0)走到(n-1,m-1),在连续穿过墙的个数小于等于k的前提下,最少走几步?

思路:bfs,但要考虑穿过的墙数目,可以通过vis三维变量来标记,第三维表示到这个点的各个墙数是否被访问过,这样又回归到最简单的bfs了

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
int dir[4][2]={-1,0,1,0,0,-1,0,1},n,m,k,a[50][50];
typedef struct node
{
    int x,y,num,z;
}N;
int vjudge(int x,int y)
{
    if(x<0||x>=n||y<0||y>=m)
        return 1;
    return 0;
}
int bfs()
{
    int vis[50][50][50]={0},i,j;//第三维用来标记连续穿过的墙的数量
    queue <N> q;
    N now,next;
    now.x=now.y=0;
    now.num=now.z=0;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        if(now.x==(n-1)&&now.y==(m-1))
            return now.num;
        for(i=0;i<4;i++)
        {
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            next.z=now.z;
            if(vjudge(next.x,next.y))
                continue;
            if(a[next.x][next.y])  //如果下一个点是墙,则连续穿过的墙数加1
                next.z++;
            else next.z=0;
            if(next.z<=k&&!vis[next.x][next.y][next.z])//如果穿过的墙没有超过最大限制并且这个点的在这个墙数上没有被访问过
            {
                next.num=now.num+1;
                vis[next.x][next.y][next.z]=1;
                q.push(next);
            }
        }
    }
    return -1;
}
int main()
{
    int t,i,j;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d",&n,&m,&k);
        for(i=0;i<n;i++)
            for(j=0;j<m;j++)
              scanf("%d",&a[i][j]);
        printf("%d\n",bfs());
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2020/3/16

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值