2021-09-26楷登电子第三题BFS

涉及到unordered_set和pair以及tuple,记录一下,感觉拿DFS做会简单很多。
输入描述:
第一行为两个正整数,分别表示上述之M,N。
接下来有M行,每一行都包含N个正整数。
后面一行有两个整数,表示初始格子的行号及列号,行号范围为[0,M-1],列号范围为[0,N-1]。
最后一行有两个整数,表示目标格子的行号及列号,行号范围为[0,M-1], 列号范围为[0,N-1]。
输出描述:
若当前位置值大于等于下一步的值则不消耗能量,若小于则消耗差值的能量
求:输出最小消耗的总能量。

#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>
using namespace std;
struct  pair_hash{
    inline size_t operator()(const pair<int,int>& p) const{
        return p.first * 10 + p.second;
    }
};
int main(){
    int m, n;
    cin >> m >> n;
    vector<vector<int>> dp(m, vector<int>(n));
    unordered_set<pair<int,int>, pair_hash> set;
    int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            cin >> dp[i][j];
        }
    }
    int res = 10000000;
    int sx,sy,ex,ey;
    cin >> sx >> sy;
    cin >> ex >> ey;
    queue<tuple<int,int,int>> q;
    q.emplace(sx,sy,0);
    set.insert({sx,sy});
    while(!q.empty()){
        auto& [x,y,z] = q.front();
        q.pop();
        if(x == ex && y == ey){
            res = min(res, z);
        }
        for(auto& d: dir){
            int nx = x + d[0];
            int ny = y + d[1];
            if(!set.count({nx,ny}) && nx >= 0 && nx < m && ny >= 0 && ny < n){
                q.emplace(nx, ny, dp[x][y] >= dp[nx][ny] ? z : z + (dp[nx][ny] - dp[x][y]));
                set.insert({nx,ny});
            }
        }
    }
    cout << res;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值