Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- 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.
- '''
- def is_feasible(new_i,new_j,row,col,arr,i,j):
- if new_i>=0 and new_i<=row and new_j>=0 and new_j<=col:
- return True
- return False
- def fun(i,j,row,col,arr,visited):
- if visited[i][j]:
- return visited[i][j]
- visited[i][j]=1 #atleast length is gonna be 1
- x=[-1,0,1,0]
- y=[0,1,0,-1]
- for k in range(4):
- new_i=i+x[k]
- new_j=j+y[k]
- if is_feasible(new_i,new_j,row,col,arr,i,j) and arr[new_i][new_j]>arr[i][j]:
- visited[i][j]=max(visited[i][j],1+ fun(new_i,new_j,row,col,arr,visited))
- return visited[i][j]
- class Solution:
- def longestIncreasingPath(self, arr: List[List[int]]) -> int:
- row=len(arr)
- col=len(arr[0])
- visited=[[0]*col for i in range(row)]
- for i in range(row):
- for j in range(col):
- if visited[i][j]==0:
- fun(i,j,row-1,col-1,arr,visited)
- return max(max(row) for row in visited)
Advertisement
Add Comment
Please, Sign In to add comment