imashutosh51

Longest Increasing Path in a matrix

Oct 29th, 2022 (edited)
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. '''
  2. In this code, we maintain a 2D DP table visited where visited[i][j] stores the length of the longest increasing path starting from cell (i, j). For each cell, if it hasn’t been computed yet, we use DFS (fun) to explore all 4 directions and update visited[i][j] by taking the maximum of 1 + path from a valid increasing neighbor. The initial value of visited[i][j] is set to 1 to count the cell itself. Passing row-1 and col-1 ensures boundary checks in is_feasible work correctly. After processing all cells, the answer is the maximum value in visited, representing the longest increasing path in the matrix.
  3. '''
  4.  
  5. def is_feasible(new_i,new_j,row,col,arr,i,j):
  6.     if new_i>=0 and new_i<=row and new_j>=0 and new_j<=col:
  7.         return True
  8.     return False
  9. def fun(i,j,row,col,arr,visited):
  10.     if visited[i][j]:
  11.         return visited[i][j]
  12.     visited[i][j]=1 #atleast length is gonna be 1
  13.  
  14.     x=[-1,0,1,0]
  15.     y=[0,1,0,-1]
  16.  
  17.     for k in range(4):
  18.         new_i=i+x[k]
  19.         new_j=j+y[k]
  20.  
  21.         if is_feasible(new_i,new_j,row,col,arr,i,j) and arr[new_i][new_j]>arr[i][j]:
  22.             visited[i][j]=max(visited[i][j],1+ fun(new_i,new_j,row,col,arr,visited))
  23.     return visited[i][j]
  24.    
  25. class Solution:
  26.     def longestIncreasingPath(self, arr: List[List[int]]) -> int:
  27.         row=len(arr)
  28.         col=len(arr[0])
  29.         visited=[[0]*col for i in range(row)]
  30.         for i in range(row):
  31.             for j in range(col):
  32.                 if visited[i][j]==0:
  33.                     fun(i,j,row-1,col-1,arr,visited)
  34.         return max(max(row) for row in visited)
  35.        
Advertisement
Add Comment
Please, Sign In to add comment