1600:Patrol Robot

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37754288/article/details/81546380

Patrol Robot

这个题还是DFS,不过每个状态除了记录位置之外,还要记录剩余穿越次数,这样一来就变成了三维DFS。对于值为1的点如果剩余穿越次数大于0且该状态未遍历过的话也可以访问。像这种四个方向的话用常量数组比较方便,没必要搞个二重循环,容易出bug。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 20;
struct P{
    int x,y,l;
    P(int a,int b,int c):x(a),y(b),l(c){}
};
int T,m,n,k,x,y;
int d[maxn][maxn][maxn+1];
int G[maxn][maxn];
int xs[4] = {-1,1,0, 0};
int ys[4] = { 0,0,1,-1};
void BFS()
{
    queue<P>q;
    q.push(P(0,0,k));
    d[0][0][k] = 0;
    while(!q.empty()){
        P t = q.front(); q.pop();
        int x = t.x,y = t.y,l = t.l;
        for(int i = 0;i < 4;i++){
            int dx = xs[i],dy = ys[i];
            if(x+dx >= 0 && x+dx < m && y+dy >= 0 && y+dy < n &&
                ((!G[x+dx][y+dy] && d[x+dx][y+dy][k] == -1) || (G[x+dx][y+dy] && l && d[x+dx][y+dy][l-1] == -1))){
                    int ll = (G[x+dx][y+dy] ? l - 1 : k);
                    d[x+dx][y+dy][ll] = d[x][y][l] + 1;
                    q.push(P(x+dx,y+dy,ll));
                    if(x+dx == m-1 && y+dy == n-1) return;
                }
        }
    }
}
int main()
{
    // freopen("data.in","r",stdin);
    // freopen("data.out","w",stdout);
    scanf("%d",&T);
    while(T--){
        memset(d,-1,sizeof(d));
        scanf("%d%d%d",&m,&n,&k);
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                scanf("%d",&G[i][j]);
            }
        }
        BFS();
        printf("%d\n",d[m-1][n-1][k]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37754288/article/details/81546380