[UVA1600]Patrol Robot(BFS)

题目大意

输入一个由0和1组成的网格表,0代表空地,1代表陷阱,小车从(1,1)出发,求到(m,n)(右下角)的最短步数,值得注意的是不能连续经过life个陷阱。

思路

BFS,每到一个节点除了位置参数外,还应该包含到这个位置的步数,和剩余的命数(还可以连续过几个陷阱)。如果符合条件:1.先前未以相同命数经过这个节点2.还未挂掉则将节点push到一个队列中。重复push和pop直到到达重点(m,n)。

代码

#include <bits/stdc++.h>
using namespace std;

const int maxn = 25;

int m, n, life, ans;     
int table[maxn][maxn];
bool vis[maxn][maxn][maxn];
int dx[] = {0, 1, 0, -1};
int dy[] = {-1, 0, 1, 0};

struct Node {
    int r, c;
    int step;
    int life;
    Node(int r, int c, int step, int life) : r(r), c(c), step(step), life(life) {}
};

void input() {
    memset(table, 0, sizeof(table));
    memset(vis, false, sizeof(vis));
    cin >> m >> n >> life;
    for(int i = 1; i <= m; i++)
        for(int j = 1; j <= n; j++)
            cin >> table[i][j];
}


Node walk(const Node & x, const int i) {
    return Node(x.r + dx[i], x.c + dy[i], x.step + 1, x.life);
}

bool is_inside(const Node & x) {
    return x.r>=1 && x.r<=m && x.c>=1 && x.c<=n;
}

void bfs()
{
    queue<Node> qu;
    qu.push(Node(1, 1, 0, life));
    while(!qu.empty())
    {
        Node u = qu.front(); 
        qu.pop();
        if(u.r == m && u.c == n){
            ans = u.step;
            return;
        }
        if(u.life >= 0)
            for(int i = 0; i < 4; i++){
                Node v = walk(u, i);
                if(table[v.r][v.c]) v.life--;
                else v.life = life;
                if(is_inside(v) && !vis[v.r][v.c][v.life] && v.life >= 0) {
                    qu.push(v);
                    vis[v.r][v.c][v.life] = true;
                }
            }
    }
    ans = -1;
}

int main()
{
    //freopen("input.txt","r",stdin);
    int T;
    cin >> T;
    while(T--)
    {
        input();
        bfs();
        cout << ans << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值