Leetcode Version

Problem Statement

Given an m x n integers matrix, return the length of the longest increasing path in matrix.

From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).

Example 1:

Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is[1, 2, 6, 9].

Example 2:

Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation:The longest increasing path is[3, 4, 5, 6]. Moving diagonally is not allowed.

Example 3:

Input: matrix = [[1]]
Output: 1

Problem Link

Longest Increasing Path in a Matrix - LeetCode

Code

// Using Memoization
class Solution {
public:
    vector<vector<int>> dp;
    
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        
        dp.resize(m,vector<int>(n,-1));
        
        int res = 0;
        
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
               
                  res = max(res, dfs(i,j,m,n,matrix));
            }
        }
        
        return res;
        
    }
    int dfs(int i,int j,int m,int n,vector<vector<int>>& matrix)
    {
        if(i<0 || j<0 ||i>m-1 ||j>n-1)
           return 0;
        
        if(dp[i][j]!=-1)
            return dp[i][j];
        
        int a=0,b=0,c=0,d=0;
        
        if(i+1<=m-1 && matrix[i+1][j]>matrix[i][j])
            a = dfs(i+1,j,m,n,matrix);
        
        if(i-1>=0 && matrix[i-1][j]>matrix[i][j])
            b = dfs(i-1,j,m,n,matrix);
        
        
        if(j+1<=n-1 && matrix[i][j+1]>matrix[i][j])
            c = dfs(i,j+1,m,n,matrix);
        
        
        if(j-1>=0 && matrix[i][j-1]>matrix[i][j])
            d = dfs(i,j-1,m,n,matrix);
        
      
        
        return dp[i][j] = 1+max({a,b,c,d});
       
        
    }
};

Interview Bit Version

Problem Statement

Given a 2D integer matrix A of size N x M.

From A[i][j] you can move to A[i+1][j], if A[i+1][j] > A[i][j], or can move to A[i][j+1] if A[i][j+1] > A[i][j].