Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 1631 · Shortest Path / Dijkstra

Path With Minimum Effort

LeetCode 1631 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Dijkstra with max() instead of +.

ಮಧ್ಯಮArrayBinary SearchDepth-First SearchBreadth-First SearchUnion-Find
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Path With Minimum Effort (LeetCode 1631) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Shortest Path / Dijkstra ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

A path's cost is its largest step, not the sum. Dijkstra still works if you relax with max(current effort, step) instead of adding — the first time the target is popped, its effort is minimal.

Approach

  1. 1

    dist grid of ∞, heap with (0, 0, 0).

  2. 2

    Pop the smallest effort; target → return.

  3. 3

    For neighbours, effort = max(cur, |height difference|); push if better.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Dijkstra (minimax)PythonO(mn log mn) time
class Solution:
    #max diff is minimum
    def minimumEffortPath(self, heights: List[List[int]]) -> int:
        m = len(heights)
        n = len(heights[0])
        dist = [[float("inf")]*n for _ in range(m)]
        heap=[(0,0,0)]
        dist[0][0]=0
        while heap:
            effort,row,col = heapq.heappop(heap)
            if row==m-1 and col==n-1:
                return dist[m-1][n-1]
            di = [0,+1,0,-1]
            dj = [+1,0,-1,0]
            for k in range(4):
                nrow= row+di[k]
                ncol = col+dj[k]
                if 0<=nrow<m and 0<=ncol<n:
                   min_effort = max(effort,abs(heights[nrow][ncol]-heights[row][col]))
                   if dist[nrow][ncol]>min_effort:
                    dist[nrow][ncol]=min_effort
                    heapq.heappush(heap,(min_effort,nrow,ncol))

        return -1
        
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Path With Minimum Effort — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Path With Minimum Effort ಹಿಂದಿನ intuition ಏನು?

A path's cost is its largest step, not the sum. Dijkstra still works if you relax with max(current effort, step) instead of adding — the first time the target is popped, its effort is minimal.

Path With Minimum Effort (LeetCode 1631) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. dist grid of ∞, heap with (0, 0, 0). 2. Pop the smallest effort; target → return. 3. For neighbours, effort = max(cur, |height difference|); push if better.

Path With Minimum Effort ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(m·n log(m·n)). Space: O(m · n). (Accepted approach: Dijkstra (minimax).)

Path With Minimum Effort ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Binary search on the effort + BFS is an alternative.