Path With Minimum Effort
LeetCode 1631 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Dijkstra with max() instead of +.
நான் 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
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.
நான் எப்படித் தீர்த்தேன்
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.