p2802

· · 题解

这道题其实本质上是一个BFS四联通,只不过他走还是不走的判断条件从判断他走没走过,改为我如果走了这里是否比我上一次走到这里的血量多,否则就不走

#include<bits/stdc++.h>
using namespace std;
struct node{
    int x, y, step;
};
int a[15][15];
int vis[15][15];
int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int n, m;
int ans = 0;
void bfs(int x, int y){
    vis[x][y] = 6;//起点的血量为6 
    queue<node>q;
    q.push({x, y, 0});
    while(q.size()){
        node t = q.front();
        q.pop();
        if(a[t.x][t.y] == 3){//判断我走到了重点 
            ans = t.step;//记录答案 
            return;
        }
        for(int i = 0; i < 4; i++){
            int dx = t.x + d[i][0], dy = t.y + d[i][1];
            int val = vis[t.x][t.y] - 1;
            if(dx < 1 || dx > n || dy < 1 || dy > m){
                continue;
            }
            if(a[dx][dy] == 0){
                continue;
            }
            if(val <= vis[dx][dy]){//判断血量是否比我上一次走到这里的血量多 
                continue;
            }
            if(a[dx][dy] == 4){//如果是鼠标 
                val = 6;//加血量 
            }
            vis[dx][dy] = val;//记录到这里的血量 
            q.push({dx, dy, t.step + 1});//step是用来记录这个位置我是第几步走的 
        }
    }
}
int main(){
    cin >> n >> m;
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++){
            cin >> a[i][j];
        }
    }
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++){
            //找起点 
            if(a[i][j] == 2){
                bfs(i, j);//从起点开始BFS 
                break;
            }
        }
    }
    if(ans != 0){//判断我是否走到了终点 
        cout << ans;
    }else{
        cout << -1;
    }
    return 0;
}