2023-12-11 LeetCode每日一题(最小体力消耗路径)

2023-12-11每日一题

一、题目编号

1631. 最小体力消耗路径

二、题目链接

点击跳转到题目位置

三、题目描述

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

一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值最大值 决定的。

请你返回从左上角走到右下角的最小 体力消耗值
示例 1:
2023-12-11 LeetCode每日一题(最小体力消耗路径)_第1张图片

示例 2:
2023-12-11 LeetCode每日一题(最小体力消耗路径)_第2张图片

示例 3:
2023-12-11 LeetCode每日一题(最小体力消耗路径)_第3张图片
提示:

  • rows == heights.length
  • columns == heights[i].length
  • 1 <= rows, columns <= 100
  • 1 <= heights[i][j] <= 106

四、解题代码

int dir[4][2] = {
    {-1, 0},
    {1, 0},
    {0, -1},
    {0, 1}
};
const int maxn = 101;

bool bfs(int height, vector>& heights, int m, int n){
    int hash[maxn * maxn + 100 + 6];
    memset(hash, 0, sizeof(hash));
    queue path;
    path.push(0 * 100 + 0);
    hash[0 * 100 + 0] = 1;
    while(!path.empty()){
        int tmp = path.front();
        path.pop();
        int x = tmp / maxn;
        int y = tmp % maxn;
        if(x == m - 1 && y == n - 1){
            return true;
        }
        for(int i = 0; i < 4; ++i){
            int tx = x + dir[i][0];
            int ty = y + dir[i][1];
            if(tx >= m || ty >= n || tx < 0 || ty < 0){
                continue;
            }
            if(hash[tx * maxn + ty] == 0 && abs(heights[tx][ty] - heights[x][y]) <= height){
                hash[tx * maxn + ty]=1;
                path.push(tx * maxn + ty);
            }
        }
    }
return false;
}

class Solution {
public:
    int minimumEffortPath(vector>& heights) {
        int left = 0, right = 999999;
        int ans = 0;
        int m = heights.size();
        int n = heights[0].size();
        while(left <= right){
            int mid = (left+right) >> 1;
            if(bfs(mid, heights, m, n) == true){
                ans = mid;
                right = mid-1;
            }
            else{
                left = mid + 1;
            }
        }
    return left;
    }
};

五、解题思路

(1) 利用图的四方向遍历。

(2) 二分答案来求解。

(3) 广度优先搜索来判断答案可不可行。

你可能感兴趣的:(LeetCode每日一题,leetcode,数据结构,算法)