Advertisement
imashutosh51

Longest Increasing Path in a matrix

Oct 29th, 2022
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. /*
  2. We will have a dp table which will store the longest possible path starting with that (i,j)
  3. Initially dp table will be having -1.
  4. now travers each possible (i,j) and call function if longest path starting from that (i,j)
  5. is not present in dp table.
  6. In function,search for all neighbours and update the dp table before returning the value.
  7. answer is ans+1 because in our code,The maximum path is not considering himself
  8. */
  9.  
  10.  
  11. int fun(vector <vector<int>> &arr,vector<vector<int>> &dp,int i,int j){
  12.     if(dp[i][j]!=-1) return dp[i][j];
  13.     int row[]={-1, 0, 1 , 0};
  14.     int col[]={0 , 1, 0, -1};
  15.     int r=arr.size(),c=arr[0].size();
  16.     int _max=0;
  17.     for(int k=0;k<4;k++){
  18.         int new_i=i+row[k];
  19.         int new_j=j+col[k];
  20.         if(new_i>=0 && new_i<r && new_j>=0 && new_j<c && arr[new_i][new_j]>arr[i][j]) _max=max(_max,fun(arr,dp,new_i,new_j)+1);
  21.     }
  22.     dp[i][j]=_max;
  23.     return _max;
  24. }
  25.  
  26. class Solution {
  27. public:
  28.     int longestIncreasingPath(vector<vector<int>>& matrix) {
  29.         vector<vector<int>> dp=matrix;
  30.         for(int i=0;i<dp.size();i++){
  31.             for(int j=0;j<dp[i].size();j++){
  32.                 dp[i][j]=-1;
  33.             }
  34.         }
  35.         int ans=0;
  36.         for(int i=0;i<matrix.size();i++){
  37.             for(int j=0;j<matrix[i].size();j++){
  38.                 if(dp[i][j]==-1) dp[i][j]=fun(matrix,dp,i,j);
  39.                 ans=max(ans,dp[i][j]);
  40.             }
  41.         }
  42.         return ans+1;
  43.     }
  44. };c
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement