LeetCode每日一题 - 1631. 最小体力消耗路径(BFS)

题目:1631. 最小体力消耗路径

Description

你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。
一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。
请你返回从左上角走到右下角的最小 体力消耗值 。

Sample

在这里插入图片描述

输入:heights = [[1,2,2],[3,8,2],[5,3,5]]
输出:2
解释:路径 [1,3,5,3,5] 连续格子的差值绝对值最大为 2 。
这条路径比路径 [1,2,2,2,5] 更优,因为另一条路径差值最大值为 3 。

Solution

优先队列+BFS
每次优先拿出当前最小的体力消耗来更新,直到找到终点。

AC Code
class Solution {
    
    
public:
    struct node
    {
    
    
	    int x, y, t;
	    node(int m_x = 0, int m_y = 0, int m_time = 0) :x(m_x), y(m_y), t(m_time) {
    
    }
	    bool operator<(const node& a) const {
    
    
		    return t > a.t;
	    }
    };
    int minimumEffortPath(vector<vector<int>>& heights) {
    
    
        bool vis[110][110]={
    
    0};
        int dx[4] = {
    
     0,1,0,-1 };
        int dy[4] = {
    
     1,0,-1,0 };
        int ex=heights.size();
        int ey=heights[0].size();
        priority_queue<node> p;
	    p.push(node(0, 0, 0));
	    while (!p.empty())
	    {
    
    
		    node temp = p.top();
		    p.pop();
		    if (vis[temp.x][temp.y]) continue;
            vis[temp.x][temp.y] = 1;
            if(temp.x==ex-1&&temp.y==ey-1){
    
    //找到答案
                return temp.t;
            }
		    int xx, yy,zz;
		    for (int i = 0; i < 4; i++) {
    
    
			    xx = temp.x + dx[i];
			    yy = temp.y + dy[i];
			    if (xx >= 0 && yy >= 0 && xx < ex && yy < ey  && vis[xx][yy] == 0) {
    
    
                    zz = abs(heights[xx][yy]-heights[temp.x][temp.y]);
                    zz = max(temp.t,zz);//更新 高度差绝对值的最大值
                    p.push(node(xx,yy,zz));
			    }
		    }
	    }
        return 0;
    }
};

希望对你有帮助。

猜你喜欢

转载自blog.csdn.net/buibuilili/article/details/113371839