Longest Increasing Path in a Matrix (H)
题目
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
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
0 <= matrix[i][j] <= 2^31 - 1
题意
给定一个矩阵,可以从任一位置出发得到一条递增的路径,求最长路径的长度。
思路
DFS+记忆化很容易解决。
代码实现
Java
class Solution {
private int[] xShift = {0, -1, 0, 1};
private int[] yShift = {-1, 0, 1, 0};
private int m, n;
public int longestIncreasingPath(int[][] matrix) {
m = matrix.length;
n = matrix[0].length;
int ans = 0;
int[][] record = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
ans = Math.max(ans, dfs(matrix, i, j, record));
}
}
return ans;
}
private int dfs(int[][] matrix, int x, int y, int[][] record) {
if (record[x][y] > 0) return record[x][y];
record[x][y] = 1;
for (int i = 0; i < 4; i++) {
int nx = x + xShift[i], ny = y + yShift[i];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && matrix[x][y] < matrix[nx][ny]) {
record[x][y] = Math.max(record[x][y], 1 + dfs(matrix, nx, ny, record));
}
}
return record[x][y];
}
}