Suppose we have 2D matrix of order m x n called height. The heights[i][j] represents the height of cell (i, j). If we are at (0, 0) cell we want to travel to the bottom-right cell, (m-1, n-1). We can move up, down, left, or right, and we wish to find a route that requires the minimum effort. In this problem the roots effort is the maximum absolute difference in heights between two consecutive cells of the route. So finally, we need to find minimum efforts needed to travel to the destination.
So, if the input is like
then the output will be 1 as the route is [2,3,4,5,6] has maximum absolute difference of 1 in consecutive cells.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
import heapq def solve(heights): r,c=len(heights),len(heights) queue=[(0,0,0)] while queue: cur=heapq.heappop(queue) c_eff=cur x=cur y=cur if x==r-1 and y==c-1: return c_eff if heights[x][y]=="": continue for dx,dy in [[1,0],[-1,0],[0,1],[0,-1]]: newx=x+dx newy=y+dy if 0<=newx<r and 0<=newy<c and heights[newx][newy]!="": eff = max(c_eff, abs(heights[newx][newy] - heights[x][y])) heapq.heappush(queue,(eff, newx, newy)) heights[x][y]="" matrix = [[2,3,4],[4,9,5],[6,4,6]] print(solve(matrix))