Problem
Given anm x n integer matrix, return the length of the longest increasing path in the matrix.
From a cell, you can move up, down, left, or right. You cannot move diagonally or outside the matrix.
The value of every next cell in the path must be strictly greater than the value of the current cell.
Example 1
Input
matrix = [[9,9,4],
[6,6,8],
[2,1,1]]
Output
4
Example 2
Input
matrix = [[3,4,5],
[3,2,6],
[2,2,1]]
Output
4
Solution
This problem can be solved using Dynamic Programming with Memoization. We consider every cell as a possible starting point and find the longest increasing path starting from that cell.For each cell
(i, j), we check its four neighboring cells. We can move to a neighbor only when its value is greater than the current cell.
The state
(i, j) represents the longest increasing path starting from cell (i, j). Once this value is calculated, we store it in the memo array so that the same cell does not need to be calculated again.
The path length for every cell is initially
1 because the current cell itself is part of the path. For every valid neighboring cell, we calculate its path length and take the maximum.
Since we only move to a cell with a greater value, the path can never return to a previous cell. Therefore, there is no cycle, and memoization can safely store the result for each cell.
class Solution {
public int longestIncreasingPath(int[][] matrix) {
int max = 0;
Integer[][] memo = new Integer[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
max = Math.max(max, dfs(matrix, i, j, memo));
}
}
return max;
}
private int dfs(int[][] matrix, int i, int j, Integer[][] memo) {
if (memo[i][j] != null)
return memo[i][j];
int down = 0;
int up = 0;
int right = 0;
int left = 0;
// Look Down (i+1, j)
if (i + 1 < matrix.length && matrix[i + 1][j] > matrix[i][j])
down = dfs(matrix, i + 1, j, memo);
// Look Up (i-1, j)
if (i - 1 >= 0 && matrix[i - 1][j] > matrix[i][j])
up = dfs(matrix, i - 1, j, memo);
// Look Right (i, j+1)
if (j + 1 < matrix[0].length && matrix[i][j + 1] > matrix[i][j])
right = dfs(matrix, i, j + 1, memo);
// Look Left (i, j-1)
if (j - 1 >= 0 && matrix[i][j - 1] > matrix[i][j])
left = dfs(matrix, i, j - 1, memo);
// 1 (current cell) + the best path found from neighbors
return memo[i][j] = 1 + Math.max(down, Math.max(up, Math.max(right, left)));
}
}
Complexity
There arem × n cells, and each cell is calculated only once. For each cell, we check four directions, which takes constant time. Therefore, the time complexity is O(m × n).
The memoization array stores one result for every cell, requiring
O(m × n) space. The recursion stack can grow up to O(m × n) in the worst case, so the overall extra space complexity is O(m × n).
Comments
No comments yet. Ask a question or share what helped.