Given a N*M matrix of integers, the task is to find the length of the Longest Decreasing Path in the matrix such that
- The starting cell and the destination cell can be any cell
- It is allowed to move from a cell (i, j) to any cell
- (i, k) where k<M, if it has a value less than value at cell (i, j)
- (k, j) where k<N, if it has a value less than value at cell (i, j)
Examples :
Input : A = {{9, 10, 11, 12}, {5, 6, 7, 8}, {1, 2, 3, 4}}
Output : 3
Explanation :
There are multiple such paths of length 3.
One such path is (1, 1) -> (2, 1) -> (3, 1)
Input : A = {{12, 11, 10, 9}, {15, 16, 17, 18}, {4, 3, 2, 1}}
Output : 5
Explanation :
There are five paths of length 5.
One of the paths : (1, 1) -> (1, 2) -> (1, 3) -> (1, 4) ->
(3, 4)
Approach :
- Initialise a dp[N][M] and set all its values to 1, since the minimum length can be 1.
- Iterate from the cell (N,M) moving left and up
- For each cell (i, j)
- for all cells (p, q) in its row and left of cell (i, j), if it has a value greater than the value at cell (i, j), update dp[p][q] = max(dp[p][q], dp[i][j]+1)
- for all cells (p, q) in its columns above cell (i, j), if it has a value greater than the value at cell (i, j), update dp[p][q] = max(dp[p][q], dp[i][j]+1)
- Iterate over the dp[][] and calculate the maximum, which is the desired output.
Implementation :
// Java Program to implement
// the above approach
class Main {
// Function to calculate the length
// of the longest decreasing path
public static void
longestIncreasingPathLength(int[][] a)
{
int n = a.length, m = a[0].length;
// dp[i][j] stores the length
// of the longest decreasing
// path starting at cell (i, j)
int dp[][] = new int[n][m];
// Initialise all cells
// with value 1
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
dp[i][j] = 1;
}
for (int i = n - 1; i >= 0; i--) {
for (int j = m - 1; j >= 0; j--) {
int val = a[i][j];
// iterate over all cells to
// the left of it in its row
for (int k = j - 1; k >= 0; k--) {
if (a[i][k] > val)
dp[i][k] = Math.max(dp[i][k],
dp[i][j] + 1);
}
// iterate over all cells
// above it in its column
for (int k = i - 1; k >= 0; k--) {
if (a[k][j] > val)
dp[k][j] = Math.max(dp[k][j],
dp[i][j] + 1);
}
}
}
int max = 0;
// Calculate the
// maximum length
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
max = Math.max(max, dp[i][j]);
}
}
System.out.println(max);
}
// Driver Code
public static void main(String[] args)
{
int a[][] = { { 9, 10, 11, 12 },
{ 5, 6, 7, 8 },
{ 1, 2, 3, 4 } };
longestIncreasingPathLength(a);
}
}
Time Complexity : O(N3)
Auxiliary Space : O(N2)