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;
}

猜你喜欢

转载自blog.csdn.net/ac_ac_/article/details/80671903