Program to find path with minimum effort in Python

PythonServer Side ProgrammingProgramming

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

234
495
646

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 −

  • r := number of rows in heights, c:= number of columns in heights
  • queue:= a queue initially store a tuple (0,0,0)
  • while queue is not empty, do
    • cur:= first item of queue and delete it from queue
    • c_eff:= cur[0]
    • x:= cur[1]
    • y:= cur[2]
    • if x is same as r-1 and y is same as c-1, then
      • return c_eff
    • if heights[x, y] is a blank string, then
      • go for next iteration
    • for each dx,dy in [[1,0],[-1,0],[0,1],[0,-1]], do
      • newx := x+dx
      • newy := y+dy
      • if 0 <= newx < r and 0 <= newy < c and heights[newx, newy] is not same as blank string, then
        • eff := maximum of c_eff and |heights[newx,newy] - heights[x,y]|
        • insert tuple (eff, newx, newy) into queue
    • heights[x, y]:= blank string

Example

Let us see the following implementation to get better understanding −

import heapq
def solve(heights):
   r,c=len(heights),len(heights[0])
   queue=[(0,0,0)]

   while queue:

      cur=heapq.heappop(queue)
      c_eff=cur[0]
      x=cur[1]
      y=cur[2]

      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))

Input

[[2,3,4],[4,9,5],[6,4,6]]

Output

1
raja
Published on 05-Oct-2021 11:49:49
Advertisements