Longest Increasing Path in a Matrix in Python

PythonServer Side ProgrammingProgramming

Suppose we have one matrix; we have to find the length of the longest increasing path. From each cell, we can either move to four directions − left, right, up or down. We cannot move diagonally or move outside of the boundary.

So, if the input is like

994
668
211

then the output will be 4 as the longest increasing path is [3, 4, 5, 6].

To solve this, we will follow these steps −

  • Define a function solve(). This will take i,j,matrix

  • if dp[i,j] is non-zero, then

    • return dp[i, j]

  • dp[i, j] := 1

  • temp := 0

  • for r in range i-1 to i+2, do

    • for c in range j-1 to j+2, do

      • if r is same as i and c is same as j or(|r-i| is same as 1 and |c-j| is same as 1) , then

        • go for the next iteration

      • if c>=0 and r>=0 and r< row count of matrix and c < col size of matrix[0] and matrix[r, c]>matrix[i, j], then

        • temp := maximum of temp, solve(r, c, matrix)

  • dp[i, j] := dp[i, j] + temp

  • return dp[i, j]

  • From the main method do the following −

  • if not matrix is non-zero, then

    • return 0

  • dp := a matrix of size same as given matrix and fill with 0

  • ans := 0

  • for i in range 0 to size of matrix, do

    • for j in range 0 to size of matrix[0], do

      • if dp[i, j] is same as 0, then

        • solve(i, j, matrix)

  • return ans

Example 

Let us see the following implementation to get better understanding −

class Solution(object):
   def solve(self,i,j,matrix):
      if self.dp[i][j]:
         return self.dp[i][j]
      self.dp[i][j] = 1
      temp = 0
      for r in range(i-1,i+2):
         for c in range(j-1,j+2):
            if r==i and c==j or (abs(r-i)==1 and abs(c-j)==1):
               continue
            if c>=0 and r>=0 and r<len(matrix) and c<len(matrix[0]) and matrix[r][c]>matrix[i][j]:
temp = max(temp,self.solve(r,c,matrix))
               self.dp[i][j]+=temp
               return self.dp[i][j]
   def longestIncreasingPath(self, matrix):
      if not matrix:
         return 0
      self.dp = [ [0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
      self.ans = 0
      for i in range(len(matrix)):
         for j in range(len(matrix[0])):
            if self.dp[i][j]==0:
               self.solve(i,j,matrix)
            self.ans = max(self.ans,self.dp[i][j])
      return self.ans

ob = Solution()
print(ob.longestIncreasingPath([[9,9,4],[6,6,8],[2,1,1]]))

Input

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

Output

4
raja
Published on 21-Jul-2020 08:25:10
Advertisements