329. Longest Increasing Path in a Matrix (Hard)
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9]
.
Example 2:
Input: nums =
[
[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.
Solutions
class Solution {
// This problem should not be categorized as hard, medium would be preferable.
private int[] R = new int[]{0, 0, -1, 1};
private int[] C = new int[]{-1, 1, 0, 0};
public int longestIncreasingPath(int[][] matrix) {
// Take care of corner cases
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
return 0;
}
int rLen = matrix.length;
int cLen = matrix[0].length;
int[][] track = new int[rLen][cLen];
int max = 1;
for (int i = 0; i < rLen; i++) {
for (int j = 0; j < cLen; j++) {
int rst = recurse(track, matrix, i, j);
max = Math.max(max, rst);
}
}
return max;
}
private int recurse(int[][] track, int[][] matrix, int row, int col) {
// if current cell is the end of path
track[row][col] = 1;
for (int i = 0; i < 4; i++) {
int nextR = row + R[i];
int nextC = col + C[i];
// exceed the boundary
if (nextR < 0 || nextR >= matrix.length || nextC < 0 || nextC >= matrix[0].length) {
continue;
}
// cannot move to smaller cell
if (matrix[nextR][nextC] <= matrix[row][col]) {
continue;
}
// only if track[nextR][nextC] == 0, it is not visited yet
if (track[nextR][nextC] == 0) {
track[nextR][nextC] = recurse(track, matrix, nextR, nextC);
} // otherwise, read the value track[nextR][nextC] directly with computation
// to reach here, [row][col] is greater than [nextR][nextC], increase the size
// of ascending sequence in which [row][col] will be included.
track[row][col] = Math.max(track[row][col], track[nextR][nextC] + 1);
}
return track[row][col];
}
}