Program to find minimum number of heights to be increased to reach destination in Python

PythonServer Side ProgrammingProgramming

Suppose we have a matrix M where M[r][c] represents the height of that cell. If we are currently at top left corner and want to go to the bottom right corner. We can move to adjacent cells (up, down, left, right) only if that the height of that adjacent cell is less than or equal to the current cell's height. We can increase the height of any number of cells before we move, so we have to find the minimum total height that needs to be increased so that we can go to the bottom right cell.

So, if the input is like

245
861

then the output will be 4, as we can take the following path [2, 4, 5, 1] and change the heights to this configuration −

555
861

To solve this, we will follow these steps −

INF := infinity

  • R, C := row number of matrix, column number of matrix

  • pq := make a priority queue using heap, and insert [0, R-1, C-1, M[-1, -1]] into it

  • dist := a map

  • dist[R-1, C-1, A[-1, -1]] := 0

  • while pq is not empty, do

    • delete one element from pq and store them into d, r, c, h

    • if dist[r, c, h] < d, then

      • go for the next iteration

    • if r and c are both 0, then

      • return d

    • for each pair (nr, nc) in [[r+1, c], [r, c+1], [r-1, c], [r, c-1]], do

      • if 0 <= nr < R and 0 <= nc < C, then

        • if d2 < dist[nr, nc, h2], then

          • dist[nr, nc, h2] := d2

          • insert [d2, nr, nc, h2] into pq

Let us see the following implementation to get better understanding −

Example

 Live Demo

import collections
import heapq
class Solution:
   def solve(self, A):
      INF = float('inf')
      R, C = len(A), len(A[0])

      pq = [[0, R-1, C-1, A[-1][-1]]]
      dist = collections.defaultdict(lambda: INF)
      dist[R-1, C-1, A[-1][-1]] = 0
      while pq:
         d, r, c, h = heapq.heappop(pq)
         if dist[r, c, h] < d:
            continue
         if r == c == 0:
            return d
         for nr, nc in [[r+1, c], [r, c+1], [r-1, c], [r, c-1]]:
            if 0 <= nr < R and 0 <= nc < C:
               h2 = max(A[nr][nc], h)
               d2 = d + max(h2 - A[nr][nc], 0)
               if d2 < dist[nr, nc, h2]:
                  dist[nr, nc, h2] = d2
                  heapq.heappush(pq, [d2, nr, nc, h2])
ob = Solution()
matrix = [
[2, 4, 5],
[8, 6, 1]
]
print(ob.solve(matrix))

Input

[[2, 4, 5],[8, 6, 1]]

Output

4
raja
Published on 08-Oct-2020 14:48:34
Advertisements