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.