攻城掠地

题目描述

今天LZY攻城小分队出动了,他们需要在尽可能短的时间内攻占敌人的大本营。战场是一个n * m的二维网格,LZY小分队初始在(0,0)点,敌军大本营在( n -1 ,m - 1)点 每个点上有一个对应的数字代表LZY小分队攻占这个据点需要耗费的时间,现在作为LZY小分队的指挥官,你需要指定一条合适的路线,使LZY小分队能用最短的时间攻占敌人大本营。

输入

测试样例由多组测试数据组成。每组测试数据第一行输入两个正整数n , m ( 1 <= n,m <= 100) 接下来输入n * m 个数字 ,每个数字不超过 500

输出

输出LZY小分队攻占敌人大本营所需要的最短时间

样例输入

3 3
1 2 3
1 2 3
1 2 3

样例输出

8

代码

#include <iostream>
#include <queue>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
#include <map>
#include <set>
#include <cstdlib>
using namespace std;
/*
 *  优先队列 + BFS
 * */
struct Node{
    int x;
    int y;
    //到达当前这个点消耗时间
    int value;
};
//排序规则 cmp 仿函数
//优先队列的自定义排序规则和sort自定义相反
struct cmp{
    bool operator()(Node a,Node b){
        return a.value > b.value;
    }
};
int n,m;
int s[105][105];
int vis[105][105];
int dir[4][2] = { {-1,0},{0,-1},{1,0},{0,1} };
// queue代表普通队列
//queue<Node> q;
//优先队列3个参数 数据类型、排序容器、排序规则
priority_queue<Node,vector<Node>,cmp> q;
int bfs(){
    while(!q.empty()){
        int len = q.size();
        for(int i = 0 ; i < len ; i ++){
            int x = q.top().x;
            int y = q.top().y;
            int value = q.top().value;
            //记得pop
            q.pop();
            //先判断是否到达终点
            if(x == n - 1 && y == m - 1)
                return value;
            //继续往四个方向扩展
            for(int j = 0 ; j < 4 ; j ++){
                int tx = x + dir[j][0];
                int ty = y + dir[j][1];
                if(tx >= 0 && ty >= 0 && tx < n && ty < m && vis[tx][ty] == 0){
                    vis[tx][ty] = 1;
                    //下一个节点的 value 等于 下一个节点的value + 当前节点的value
                    q.push({tx,ty,s[tx][ty] + value});
                }
            }
        }
    }
}
int main()
{
//    freopen("test.in","r",stdin);
//    freopen("test.out","w",stdout);
    ios::sync_with_stdio(false);
    while(cin >> n >> m){
        //检查队列是否清空了
        while (!q.empty())
            q.pop();
        memset(vis,0, sizeof(vis));
        for(int i = 0 ; i < n ; i ++){
            for(int j = 0 ; j < m ; j ++){
                cin >> s[i][j];
            }
        }
        //将LZY初始坐标以及耗时压入队列
        q.push({0,0,s[0][0]});
        int ans = bfs();
        cout << ans << endl;
    }
    return 0;
}
发布了22 篇原创文章 · 获赞 1 · 访问量 436

猜你喜欢

转载自blog.csdn.net/weixin_46396354/article/details/105014367