Longest Increasing Path in a Matrix | Practice | GeeksforGeeks

Given a matrix with n rows and m columns. Your task is to find the length of the longest increasing path in matrix, here increasing path means that the value in the specified path increases. For example if a path of length k has values a1, a2, a3, .... ak  , then for every i from [2,k] this condition must hold ai > ai-1.  No cell should be revisited in the path.
From each cell, you can either move in four directions: left, right, up, or down. You are not allowed to move diagonally or move outside the boundary.

Example 1:
Input:
n = 3, m = 3
matrix[][] = {{1 2 3},
              {4 5 6},
              {7 8 9}}
Output: 
5
Explanation: 
The longest increasing path is 
{1, 2, 3, 6, 9}. 

Example 2:
Input:
n = 3, m = 3
matrix[][] = {{3 4 5},
              {6 2 6},
              {2 2 1}}
Output: 
4
Explanation:
The longest increasing path is
{3, 4, 5, 6}.

Your Task:
You only need to implement the given function longestIncreasingPath() which takes the two integers n and m and the matrix matrix as input parameters, and returns the length of the longest increasing path in matrix.

Expected Time Complexity: O(n*m)
Expected Auxiliary Space: O(n*m)

Constraints:
1 ≤ n,m ≤ 1000
0 ≤ matrix[i] ≤ 230
0
yashh27112 months ago
DFS + Dp
class Solution { public:   int longestIncreasingPath(vector<vector<int>>& matrix, int numRows, int numCols) {
       // Code here       vector<vector<int>> dp = vector<vector<int>>(numRows, vector<int>(numCols, -1));       int longestPath = 1;       for(int row = 0; row < numRows; row++)       {           for(int col = 0; col < numCols; col++)           {               if(dp[row][col] == -1)               {                   longestPath = max(longestPath, dfs(matrix, row, col, dp));               }           }       }                     return longestPath;   }      private:   int dx[4] = {1,0,-1,0};   int dy[4] = {0,1,0,-1};   int dfs(const vector<vector<int>>& matrix, int row, int col, vector<vector<int>>& dp)   {       if(dp[row][col] != -1) return dp[row][col];              int longestPath = 0;       for(int dir = 0; dir < 4; dir++)       {           int nextRow = row + dx[dir];           int nextCol = col + dy[dir];           if(nextRow >= 0 and nextCol >= 0 and nextRow < matrix.size() and nextCol < matrix[0].size())           {               if(matrix[nextRow][nextCol] > matrix[row][col])               {                   longestPath = max(longestPath, dfs(matrix, nextRow, nextCol, dp));               }           }       }              return dp[row][col] = longestPath + 1;   }};
0
debjyotichattopadhyay3 months ago
//JAVA top down memoization solution
class Solution {
    /*You are required to complete this method*/
    int longestIncreasingPath(int mat[][], int n, int m) {
        int store[][]=new int [n][m];
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                store[i][j]=-1;
            }
        }
        int maxLen=Integer.MIN_VALUE;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                maxLen=Math.max(maxLen,dp(i,j,mat,store));
            }
        }
        return(maxLen);
    }//longestIncreasingPath
    public int dp(int cr,int cc,int mat[][],int store[][]){
        
        if(store[cr][cc]!=-1)
            return(store[cr][cc]);
        
        int maxLen=0;
        
        if(cr-1>=0 &&mat[cr-1][cc]>mat[cr][cc])
            maxLen=Math.max(maxLen,dp(cr-1,cc,mat,store));
        if(cc-1>=0 && mat[cr][cc-1] > mat[cr][cc])
            maxLen=Math.max(maxLen,dp(cr,cc-1,mat,store));
        if(cr+1<mat.length && mat[cr+1][cc]>mat[cr][cc])
            maxLen=Math.max(maxLen,dp(cr+1,cc,mat,store));
        if(cc+1<mat[0].length && mat[cr][cc+1]>mat[cr][cc])
            maxLen=Math.max(maxLen,dp(cr,cc+1,mat,store));
        
        store[cr][cc]=1+maxLen;
        return(store[cr][cc]);
    }//dp
}//Solution
0
Rohit Vishwakarma7 months ago
Rohit Vishwakarma
     Dynamic Programming DFS(memoization on dfs) O(n^2)    int dp[1001][1001];       int dfs(int i , int j, vector<vector<int>> & matrix, int curr_val) {        if(i < 0 || j < 0 || i >= matrix.size() || j >= matrix[0].size() || curr_val >= matrix[i][j]) {            return 0;         }        if(dp[i][j] != -1) {            return dp[i][j];         }        int temp = matrix[i][j];         int one = 1 + dfs(i+1, j, matrix, temp);         int two = 1 + dfs(i, j+1, matrix, temp);          int three = 1 + dfs(i-1, j, matrix, temp);         int four = 1 + dfs(i,j-1, matrix, temp);          return dp[i][j] = max({one, two, three, four});     }      int longestIncreasingPath(vector<vector<int>>& matrix, int n, int m) {          int length = 0;         memset(dp, -1, sizeof(dp));          for(int i = 0; i < n; ++i) {            for(int j = 0; j < m; ++j) {                int curr = INT_MIN;                 int temp = dfs(i,j,matrix,curr);                 length = max(length, temp);              }        }        return length;      }
Dynamic Programming DFS(memoization on dfs) O(n^2)
0
Yashraj Labde9 months ago
Yashraj Labde
DFS wont work as we need O(n*n), think this problem as an application of topological sort.
0
Sai Akhil Mittapally10 months ago
Sai Akhil Mittapally
Easy C++ SOLUTION:class Solution {  public:    int IncreasingPath(vector<vector<int>>& arr,int i,int j,int n,int m,vector<vector<int>>&dp){        if(dp[i][j]!=-1){            return dp[i][j];        }        int max1=0,max2=0,max3=0,max4=0;        if(i+1<n&&arr[i][j]<arr[i+1][j]){ max1="IncreasingPath(arr,i+1,j,n,m,dp)+1;" }="" if(i-1="">=0&&arr[i][j]<arr[i-1][j]){ max2="IncreasingPath(arr,i-1,j,n,m,dp)+1;" }="" if(j-1="">=0&&arr[i][j]<arr[i][j-1]){ max3="IncreasingPath(arr,i,j-1,n,m,dp)+1;" }="" if(j+1<m&&arr[i][j]<arr[i][j+1]){="" max4="IncreasingPath(arr,i,j+1,n,m,dp)+1;" }="" if(max(max(max1,max2),max(max3,max4))="=0){" return="" 1;="" }="" return="" dp[i][j]="max(max(max1,max2),max(max3,max4));" }="" int="" longestincreasingpath(vector<vector<int="">>& arr, int n, int m) {        // Code here        vector<vector<int>>dp(n,vector<int>(m,-1));        int maxi=INT_MIN;        for(int i=0;i<n;i++){ for(int="" j="0;j&lt;m;j++){" maxi="max(IncreasingPath(arr,i,j,n,m,dp),maxi);" }="" }="" return="" maxi;="" }="" };="">
0
Nihal Chaturvedi10 months ago
Nihal Chaturvedi
Easy approach -> Use DFS + MemorizationCreate a dp of size n*mWhat we are going to store in our dp[i][j] is the Lonest Increasing Pathfrom row =i and col = jWe will use DFS to Reach the maximum depth i.e. the longest increasing path here .To avoid calculating the Longest Increasing path for a cell multiple times we will use the concept of memorization and store the value in our dpHere we don't need to keep a visited matrix as Suppose the matrix is :       3          2       5          6Now from 3 we will go to 5 Now from 5 since 3 is smaller than 5 so we will never go to 3 .So we will never go toward the path from which we are coming .
 https://uploads.disquscdn.c...
0
Shruti Agarwal1 year ago
Shruti Agarwal
The idea is to start traversing from each block in matrix and store the answer computed for that block in a memo.
class Solution {private:    vector<vector<int>> dp;    vector<vector<int>> M;    int R,C;    bool isValid(int i,int j){        if(i<0 or i>=R or j<0 or j>=C) return false;        return true;    }    int x[4]{0,0,1,-1};    int y[4]{1,-1,0,0};    int dfs(int i,int j)    {        if(dp[i][j]!=-1) return dp[i][j];        int maxPath=0;        for(int k=0;k<4;k++)        {            int ni=i+x[k];            int nj=j+y[k];            if(isValid(ni,nj) and M[ni][nj]>M[i][j]) maxPath=max(maxPath,dfs(ni,nj));        }        return dp[i][j]=1+maxPath;    }public:    int longestIncreasingPath(vector<vector<int>>& m) {        R=m.size();        C=m[0].size();        M=m;        dp.resize(R,vector<int>(C,-1));        int ans=0;        for(int i=0;i<r;i++) {="" for(int="" j="0;j&lt;C;j++)" {="" ans="max(ans,dfs(i,j));" }="" }="" return="" ans;="" }="" };="">
0
FuckItBot1 year ago
FuckItBot
@GFG dfs with memorization solution is getting accepted, whereas the time constraint clearly mentions O(n*m) time complexity. Please change the time constraint  :/
0
Hrishikesh Rai1 year ago
Hrishikesh Rai
CODE EASY TO UNDERSTANDhttps://ide.geeksforgeeks.o...IF AGAIN HAVING ANY PROBLEM, WATCH THIShttps://youtu.be/FjZdJ4aHdpU
0
Bharat Gupta
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.