The Wayback Machine - https://web.archive.org/web/20241001024620/https://www.geeksforgeeks.org/longest-increasing-path-matrix/
Open In App

Longest Increasing Path in Matrix

Last Updated : 19 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Hard
35.34%
7.3K

Given a matrix of N rows and M columns. From m[i][j], we can move to m[i+1][j], if m[i+1][j] > m[i][j], or can move to m[i][j+1] if m[i][j+1] > m[i][j]. The task is print longest path length if we start from (0, 0).

Examples: 

Input : N = 4, M = 4
        m[][] = { { 1, 2, 3, 4 },
                  { 2, 2, 3, 4 },
                  { 3, 2, 3, 4 },
                  { 4, 5, 6, 7 } };
Output : 7
Longest path is 1 2 3 4 5 6 7.

Input : N = 2, M =2
        m[][] = { { 1, 2 },
                  { 3, 4 } };
Output :3
Longest path is either 1 2 4 or 
1 3 4.

The idea is to use dynamic programming. Maintain the 2D matrix, dp[][], where dp[i][j] store the value of the length of the longest increasing sequence for submatrix starting from the ith row and jth column. 

Let the longest increasing sub sequence values for m[i+1][j] and m[i][j+1] be known already as v1 and v2 respectively. Then the value for m[i][j] will be max(v1, v2) + 1. 
We can start from m[n-1][m-1] as the base case with the length of longest increasing subsequence be 1, moving upwards and leftwards updating the value of cells. Then the LIP value for cell m[0][0] will be the answer. 

Below is the implementation of this approach: 

C++




// CPP program to find longest increasing
// path in a matrix.
#include <bits/stdc++.h>
#define MAX 10
using namespace std;
 
// Return the length of LIP in 2D matrix
int LIP(int dp[][MAX], int mat[][MAX], int n, int m, int x, int y)
{
    // If value not calculated yet.
    if (dp[x][y] < 0) {
        int result = 0;
 
        // If reach bottom right cell, return 1.
        if (x == n - 1 && y == m - 1)
            return dp[x][y] = 1;
 
        // If reach the corner of the matrix.
        if (x == n - 1 || y == m - 1)
            result = 1;
 
        // If value greater than below cell.
        if(x != n-1) // x reaches last row
         if (mat[x][y] < mat[x + 1][y])
             result = 1 + LIP(dp, mat, n, m, x + 1, y);
 
        // If value greater than left cell.
        if(y != m-1) // y reaches last column
         if (mat[x][y] < mat[x][y + 1])
             result = max(result, 1 + LIP(dp, mat, n, m, x, y + 1));
 
        dp[x][y] = result;
    }
 
    return dp[x][y];
}
 
// Wrapper function
int wrapper(int mat[][MAX], int n, int m)
{
    int dp[MAX][MAX];
    memset(dp, -1, sizeof dp);
 
    return LIP(dp, mat, n, m, 0, 0);
}
 
// Driven Program
int main()
{
    int mat[][MAX] = {
        { 1, 2, 3, 4 },
        { 2, 2, 3, 4 },
        { 3, 2, 3, 4 },
        { 4, 5, 6, 7 },
    };
    int n = 4, m = 4;
    cout << wrapper(mat, n, m) << endl;
 
    return 0;
}


Java




// Java program to find longest increasing
// path in a matrix.
import java.util.*;
 
class GFG {
 
    // Return the length of LIP in 2D matrix
    static int LIP(int dp[][], int mat[][], int n,
                   int m, int x, int y)
    {
        // If value not calculated yet.
        if (dp[x][y] < 0) {
            int result = 0;
 
             // If reach bottom right cell, return 1.
            if (x == n - 1 && y == m - 1)
                return dp[x][y] = 1;
 
            // If reach the corner of the matrix.
            if (x == n - 1 || y == m - 1)
                result = 1;
 
            // If value greater than below cell.
            if (x + 1 < n && mat[x][y] < mat[x + 1][y])
                result = 1 + LIP(dp, mat, n, m, x + 1, y);
 
            // If value greater than left cell.
            if (y + 1 < m && mat[x][y] < mat[x][y + 1])
                result = Math.max(result, 1 + LIP(dp, mat, n, m, x, y + 1));
 
            dp[x][y] = result;
        }
 
        return dp[x][y];
    }
 
    // Wrapper function
    static int wrapper(int mat[][], int n, int m)
    {
        int dp[][] = new int[10][10];
        for (int i = 0; i < 10; i++)
            Arrays.fill(dp[i], -1);
 
        return LIP(dp, mat, n, m, 0, 0);
    }
 
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int mat[][] = {
            { 1, 2, 3, 4 },
            { 2, 2, 3, 4 },
            { 3, 2, 3, 4 },
            { 4, 5, 6, 7 },
        };
        int n = 4, m = 4;
        System.out.println(wrapper(mat, n, m));
    }
}
 
// This code is contributed by Arnav Kr. Mandal.


Python3




# Python3 program to find longest
# increasing path in a matrix.
MAX = 20
 
# Return the length of
# LIP in 2D matrix
def LIP(dp, mat, n, m, x, y):
     
    # If value not calculated yet.
    if (dp[x][y] < 0):
        result = 0
         
        #  // If reach bottom right cell, return 1
        if (x == n - 1 and y == m - 1):
            dp[x][y] = 1
            return dp[x][y]
 
        # If reach the corner
        # of the matrix.
        if (x == n - 1 or y == m - 1):
            result = 1
 
        # If value greater than below cell.
        if (x + 1 < n and mat[x][y] < mat[x + 1][y]):
            result = 1 + LIP(dp, mat, n,
                            m, x + 1, y)
 
        # If value greater than left cell.
        if (y + 1 < m and mat[x][y] < mat[x][y + 1]):
            result = max(result, 1 + LIP(dp, mat, n,
                                        m, x, y + 1))
        dp[x][y] = result
    return dp[x][y]
 
# Wrapper function
def wrapper(mat, n, m):
    dp = [[-1 for i in range(MAX)]
            for i in range(MAX)]
    return LIP(dp, mat, n, m, 0, 0)
 
# Driver Code
mat = [[1, 2, 3, 4 ],
    [2, 2, 3, 4 ],
    [3, 2, 3, 4 ],
    [4, 5, 6, 7 ]]
n = 4
m = 4
print(wrapper(mat, n, m))
 
# This code is contributed
# by Sahil Shelangia


C#




// C# program to find longest increasing
// path in a matrix.
using System;
 
public class GFG {
 
    // Return the length of LIP in 2D matrix
    static int LIP(int[, ] dp, int[, ] mat, int n,
                   int m, int x, int y)
    {
        // If value not calculated yet.
        if (dp[x, y] < 0) {
            int result = 0;
 
            // If reach bottom right cell, return 1.
            if (x == n - 1 && y == m - 1)
                return dp[x, y] = 1;
 
            // If reach the corner of the matrix.
            if (x == n - 1 || y == m - 1)
                result = 1;
 
            // If value greater than below cell.
            if (x + 1 < n && mat[x, y] < mat[x + 1, y])
                result = 1 + LIP(dp, mat, n, m, x + 1, y);
 
            // If value greater than left cell.
            if (y + 1 < m && mat[x, y] < mat[x, y + 1])
                result = Math.Max(result, 1 + LIP(dp, mat, n, m, x, y + 1));
 
            dp[x, y] = result;
        }
 
        return dp[x, y];
    }
 
    // Wrapper function
    static int wrapper(int[, ] mat, int n, int m)
    {
        int[, ] dp = new int[10, 10];
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                dp[i, j] = -1;
            }
        }
 
        return LIP(dp, mat, n, m, 0, 0);
    }
 
    /* Driver code */
    public static void Main()
    {
        int[, ] mat = {
            { 1, 2, 3, 4 },
            { 2, 2, 3, 4 },
            { 3, 2, 3, 4 },
            { 4, 5, 6, 7 },
        };
        int n = 4, m = 4;
        Console.WriteLine(wrapper(mat, n, m));
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript




<script>
    // Javascript program to find longest increasing path in a matrix.
     
    // Return the length of LIP in 2D matrix
    function LIP(dp, mat, n, m, x, y)
    {
        // If value not calculated yet.
        if (dp[x][y] < 0) {
            let result = 0;
   
            // If reach bottom right cell, return 1.
            if (x == n - 1 && y == m - 1)
                return dp[x][y] = 1;
   
            // If reach the corner of the matrix.
            if (x == n - 1 || y == m - 1)
                result = 1;
   
            // If value greater than below cell.
            if (x + 1 < n && mat[x][y] < mat[x + 1][y])
                result = 1 + LIP(dp, mat, n, m, x + 1, y);
   
            // If value greater than left cell.
            if (y + 1 < m && mat[x][y] < mat[x][y + 1])
                result = Math.max(result, 1 + LIP(dp, mat, n, m, x, y + 1));
   
            dp[x][y] = result;
        }
   
        return dp[x][y];
    }
   
    // Wrapper function
    function wrapper(mat, n, m)
    {
        let dp = new Array(10);
        for (let i = 0; i < 10; i++)
        {
            dp[i] = new Array(10);
            for (let j = 0; j < 10; j++)
            {
                dp[i][j] = -1;
            }
        }
   
        return LIP(dp, mat, n, m, 0, 0);
    }
     
    let mat = [
            [ 1, 2, 3, 4 ],
            [ 2, 2, 3, 4 ],
            [ 3, 2, 3, 4 ],
            [ 4, 5, 6, 7 ],
        ];
    let n = 4, m = 4;
    document.write(wrapper(mat, n, m));
     
</script>


Output

7

Time Complexity: O(N*M).
Space Complexity: O(N*M)

 



Similar Reads

Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
Given a connected graph with N vertices and M edges. The task is to find the shortest path from source to the destination vertex such that the difference between adjacent edge weights in the shortest path change from positive to negative and vice versa ( Weight(E1) > Weight(E2) < Weight(E3) .... ). If no such path exists then print -1. Exampl
13 min read
Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Longest path in a Matrix from a specific source cell to destination cell
Given a matrix mat[][], and the coordinates of source and destination node, the task is to find the length of the longest path from source to destination. Example: Input: mat[][] = {{5, 6, 7, 8}, {4, 1, 0, 9}, {3, 2, 11, 10}}, src = {1, 1}, dest = {2, 2}Output: 11Explanation: The longest path between the coordinates (1, 1) and (2, 2) has 11 nodes a
9 min read
Find the longest path in a matrix with given constraints
Given a n*n matrix where all numbers are distinct, find the maximum length path (starting from any cell) such that all cells along the path are in increasing order with a difference of 1. We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1) or (i-1, j) or (i, j-1) with the condition that the adjacent cells
13 min read
Check if it is possible to make the given matrix increasing matrix or not
Given a matrix of N X M of positive integers, the task is to find out whether it is possible to make the matrix increasing or not. Print the matrix constructed otherwise print -1. Matrix elements should be greater than zero. A matrix is said to be increasing matrix if: For each row, the elements are in the increasing order.For each column, the elem
10 min read
Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation
Given a string S consisting of N digits, the task is to partition the string into at most two increasing subsequences such that concatenation of them also forms an increasing string. If it is not possible to do so, then print "-1". Examples: Input: S = “040425524644”Output: 0022444 44556Explanation:One of the possible way to partition the given str
10 min read
Shortest path to traverse all the elements of a circular array in increasing order
There are N distinct integers arranged on a circle. The distance between any two adjacent numbers is 1. The task is to travel on this circle starting with the smallest number, then moving to the second smallest, third smallest, and so on until the largest number and print the minimum travel distance. Examples: Input: arr[] = {3, 6, 5, 1, 2, 4} Outp
6 min read
Maximum Consecutive Increasing Path Length in Binary Tree
Given a Binary Tree find the length of the longest path which comprises of nodes with consecutive values in increasing order. Every node is considered as a path of length 1. Examples: 10 / \ / \ 11 9 / \ /\ / \ / \ 13 12 13 8 Maximum Consecutive Path Length is 3 (10, 11, 12) Note: 10, 9 ,8 is NOT considered since the nodes should be in increasing o
10 min read
Construction of Longest Increasing Subsequence (N log N)
In my previous post, I have explained about longest increasing sub-sequence (LIS) problem in detail. However, the post only covered code related to querying size of LIS, but not the construction of LIS. I left it as an exercise. If you have solved, cheers. If not, you are not alone, here is code. If you have not read my previous post, read here. No
10 min read
Longest Monotonically Increasing Subsequence Size (N log N): Simple implementation
Given an array of random numbers, find the longest monotonically increasing subsequence (LIS) in the array. If you want to understand the O(NlogN) approach, it's explained very clearly here. In this post, a simple and time-saving implementation of O(NlogN) approach using stl is discussed. Below is the code for LIS O(NlogN): Implementation: C/C++ Co
5 min read
Print the longest increasing consecutive subarray
Given an array arr[] of size N, the task is to print the longest increasing subarray such that elements in the subarray are consecutive integers. Examples: Input: arr[] = {1, 9, 3, 4, 20, 2}Output: {3, 4}Explanation: The subarray {3, 4} is the longest subarray of consecutive elements Input: arr[] = {36, 41, 56, 32, 33, 34, 35, 43, 32, 42}Output: {3
5 min read
Longest Increasing Odd Even Subsequence
Given an array of size n. The problem is to find the length of the subsequence in the given array such that all the elements of the subsequence are sorted in increasing order and also they are alternately odd and even. Note that the subsequence could start either with the odd number or with the even number. Examples: Input : arr[] = {5, 6, 9, 4, 7,
8 min read
Length of longest increasing circular subarray
Given an array containing n numbers. The problem is to find the length of the longest contiguous subarray in a circular manner such that every element in the subarray is strictly greater than its previous element in the same subarray. Time Complexity should be O(n). Examples: Input : arr[] = {2, 3, 4, 5, 1} Output : 5 {2, 3, 4, 5, 1} is the subarra
12 min read
Length of the longest alternating increasing decreasing subarray
Given an array arr[], the task is to find the length of the longest alternating subarray. A subarray {x1, x2, .. xn} is an alternating increasing decreasing sequence if its elements satisfy one of the following relations : x1 < x2 > x3 < x4 > x5 < …. xn or x1 > x2 < x3 > x4 < x5 > …. xn Example: Input: arr = {1, 2, 3,
15+ min read
Printing longest Increasing consecutive subsequence
Given n elements, write a program that prints the longest increasing subsequence whose adjacent element difference is one. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 3 4 5 6 7 8 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6, 7, 8, 3, 4, 5, 9, 10} O
8 min read
Length of Longest increasing sequence of nodes in a given Graph
Given a graph root, the task is to find the length of the longest increasing sequence in the graph. Example: Input: root = 7----17 / \ 1----2----5 4 / \ \ 11 6----8 / 12Output: 6 Explanation: The longest increasing sequence in the graph consists of the nodes 1, 2, 5, 6, 8, 12 Input: 2 / \ 3 1 / \ 5 6Output: 4 Approach: The given problem can be solv
13 min read
Length of the longest increasing subsequence such that no two adjacent elements are coprime
Given an array arr[] of size N. The task is to find the length of the longest subsequence from the given array such that the sequence is strictly increasing and no two adjacent elements are coprime. Note: The elements in the given array are strictly increasing in order (1 <= a[i] <= 105) Examples: Input : a[] = { 1, 2, 3, 4, 5, 6} Output : 3
9 min read
Length of longest increasing subsequence in a string
Given a string S, the task is to find the length of the longest increasing subsequence present in the given string. A sequence of characters placed in increasing order of their ASCII values is called an increasing sequence. Examples: Input: S = "abcfgffs"Output: 6Explanation: Subsequence "abcfgs" is the longest increasing subsequence present in the
7 min read
Longest Increasing Subsequence using BIT
Given an array arr, the task is to find the length of The Longest Increasing Sequence using Binary Indexed Tree (BIT) Examples: Input: arr = {6, 5, 1, 3, 2, 4, 8, 7} Output: 4 Explanation: The possible subsequences are {1 2 4 7}, {1 2 4 8}, {1 3 4 8}, {1 3 4 7} Now insert the elements one by one from left to right: 6 is inserted: max length till 5
13 min read
Longest increasing sub-sequence formed by concatenating array to itself N times
Given an array arr[] of size N, the task is to find the length of the longest increasing subsequence in the array formed by the concatenation of the arr[] to itself at the end N times.Examples: Input: arr[] = {3, 2, 1}, N = 3 Output: 3 Explanation: The array formed by the concatenation - {3, 2, 1, 3, 2, 1, 3, 2, 1} The longest increasing subsequenc
5 min read
Length of longest increasing index dividing subsequence
Given an array arr[] of size N, the task is to find the longest increasing sub-sequence such that index of any element is divisible by index of previous element (LIIDS). The following are the necessary conditions for the LIIDS:If i, j are two indices in the given array. Then: i < jj % i = 0arr[i] < arr[j] Examples: Input: arr[] = {1, 2, 3, 7,
7 min read
Longest increasing sequence by the boundary elements of an Array
Given an array arr[] of length N with unique elements, the task is to find the length of the longest increasing subsequence that can be formed by the elements from either end of the array.Examples: Input: arr[] = {3, 5, 1, 4, 2} Output: 4 Explanation: The longest sequence is: {2, 3, 4, 5} Pick 2, Sequence is {2}, Array is {3, 5, 1, 4} Pick 3, Seque
8 min read
Longest Increasing Subsequence having sum value atmost K
Given an integer array arr[] of size N and an integer K. The task is to find the length of the longest subsequence whose sum is less than or equal to K. Example: Input: arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15} K = 40 Output: 5 Explanation: If we select subsequence {0, 1, 3, 7, 15} then total sum will be 26, which is less than
5 min read
Longest increasing subsequence which forms a subarray in the sorted representation of the array
Given an array arr[] of N integers, the task is to find the length of the longest increasing subsequence such that it forms a subarray when the original array is sorted. Examples: Input: arr[] = { 2, 6, 4, 8, 2, 9 }Output: 3Explanation: Sorted array: {2, 2, 4, 6, 8, 9}All possible non-decreasing sequences of the original array are {2}, {6}, {4}, {8
11 min read
Maximize length of longest increasing prime subsequence from the given array
Given an array, arr[] of size N, the task is to find the length of the longest increasing prime subsequence possible by performing the following operations. If arr[i] is already a prime number, no need to update arr[i].Update non-prime arr[i] to the closest prime number less than arr[i].Update non-prime arr[i] to the closest prime number greater th
13 min read
Length of longest increasing prime subsequence from a given array
Given an array arr[] consisting of N positive integers, the task is to find the length of the longest increasing subsequence consisting of Prime Numbers in the given array. Examples: Input: arr[] = {1, 2, 5, 3, 2, 5, 1, 7}Output: 4Explanation:The Longest Increasing Prime Subsequence is {2, 3, 5, 7}.Therefore, the answer is 4. Input: arr[] = {6, 11,
9 min read
Length of longest increasing absolute even subsequence
Given an array arr[] consisting of N integers, the task is to find the length of the longest increasing absolute even subsequence. An increasing absolute even subsequence is an increasing subsequence of array elements having absolute difference between adjacent pairs as even. Examples: Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60} Output: 4Explana
7 min read
Length of the longest increasing subsequence which does not contain a given sequence as Subarray
Given two arrays arr[] and arr1[] of lengths N and M respectively, the task is to find the longest increasing subsequence of array arr[] such that it does not contain array arr1[] as subarray. Examples: Input: arr[] = {5, 3, 9, 3, 4, 7}, arr1[] = {3, 3, 7}Output: 4Explanation: Required longest increasing subsequence is {3, 3, 4, 7}. Input: arr[] =
14 min read
Longest increasing subsequence consisting of elements from indices divisible by previously selected indices
Given an array arr[] consisting of N positive integers, the task is to find the length of the longest increasing subsequence possible by selecting elements from indices that are divisible by all the previously selected indices. Note: Consider 1-based indexing Examples: Input: arr[] = {1, 4, 2, 3, 6, 4, 9}Output: 3Explanation: The optimal way is to
6 min read
Longest increasing sequence possible by the boundary elements of an Array
Given an array arr[] of length N consisting of positive integers, the task is to find the longest increasing subsequence that can be formed by the elements from either end of the array. Examples : Input: N=4 arr[] ={ 1, 4, 2, 3 }Output: 1 3 4Explanation: Append arr[0] to the sequence. Sequence = {1}. Array = {4, 2, 3}.Append arr[2] to the sequence.
14 min read
Article Tags :
Practice Tags :