Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- We will have a dp table which will store the longest possible path starting with that (i,j)
- Initially dp table will be having -1.
- now travers each possible (i,j) and call function if longest path starting from that (i,j)
- is not present in dp table.
- In function,search for all neighbours and update the dp table before returning the value.
- answer is ans+1 because in our code,The maximum path is not considering himself
- */
- int fun(vector <vector<int>> &arr,vector<vector<int>> &dp,int i,int j){
- if(dp[i][j]!=-1) return dp[i][j];
- int row[]={-1, 0, 1 , 0};
- int col[]={0 , 1, 0, -1};
- int r=arr.size(),c=arr[0].size();
- int _max=0;
- for(int k=0;k<4;k++){
- int new_i=i+row[k];
- int new_j=j+col[k];
- 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);
- }
- dp[i][j]=_max;
- return _max;
- }
- class Solution {
- public:
- int longestIncreasingPath(vector<vector<int>>& matrix) {
- vector<vector<int>> dp=matrix;
- for(int i=0;i<dp.size();i++){
- for(int j=0;j<dp[i].size();j++){
- dp[i][j]=-1;
- }
- }
- int ans=0;
- for(int i=0;i<matrix.size();i++){
- for(int j=0;j<matrix[i].size();j++){
- if(dp[i][j]==-1) dp[i][j]=fun(matrix,dp,i,j);
- ans=max(ans,dp[i][j]);
- }
- }
- return ans+1;
- }
- };c
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement