엔지니어 게시판
LeetCode 솔루션 분류

1631. Path With Minimum Effort

컨텐츠 정보

본문

[LeetCode 시즌 3] 2022년 4월 27일 문제입니다.

https://leetcode.com/problems/path-with-minimum-effort/ 


[Medium] 1631. Path With Minimum Effort

You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move updownleft, or right, and you wish to find a route that requires the minimum effort.

A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.

Return the minimum effort required to travel from the top-left cell to the bottom-right cell.

 

Example 1:

Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.

Example 2:

Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].

Example 3:

Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.

 

Constraints:

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

관련자료

댓글 1

austin님의 댓글

  • 익명
  • 작성일
C++ Dijkstra solution
Runtime: 204 ms, faster than 77.24% of C++ online submissions for Path With Minimum Effort.
Memory Usage: 31 MB, less than 51.34% of C++ online submissions for Path With Minimum Effort.
class Solution {
public:
    int minimumEffortPath(vector<vector<int>>& heights) {
        typedef tuple<int, int, int> pos; // cost, y, x
        priority_queue<pos, vector<pos>, greater<pos>> q;
        const size_t h = heights.size(), w = heights[0].size();
        vector<vector<bool>> v(h, vector<bool>(w));
        q.emplace(0, 0, 0);
        while(!q.empty()) {
            auto[cost, y ,x] = q.top();
            if (y == h-1 && x == w-1) return cost;
            q.pop();
            if (v[y][x]) continue;
            v[y][x] = true;
            for(auto [dy, dx] : vector<pair<int, int>>{{1,0}, {-1,0}, {0,1}, {0,-1}}) {
                auto [ny, nx] = tuple(y + dy, x + dx);
                if (ny < 0 || nx < 0 || ny == h || nx == w || v[ny][nx]) continue;
                q.emplace(max(cost, abs(heights[ny][nx] - heights[y][x])), ny, nx);
            }
        }
        return -1;
    }
};
전체 410 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 617 명
  • 오늘 방문자 4,173 명
  • 어제 방문자 9,517 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,599 명
알림 0