給定一個整數矩陣,找出最長遞增路徑的長度。
對于每個單元格,你可以往上,下,左,右四個方向移動。 你不能在對角線方向上移動或移動到邊界外(即不允許環繞)。
示例 1:
輸入: nums =?
[
? [9,9,4],
? [6,6,8],
? [2,1,1]
]?
輸出: 4?
解釋: 最長遞增路徑為?[1, 2, 6, 9]。
示例 2:
輸入: nums =?
[
? [3,4,5],
? [3,2,6],
? [2,2,1]
]?
輸出: 4?
解釋: 最長遞增路徑是?[3, 4, 5, 6]。注意不允許在對角線方向上移動。
思路:記憶化搜索即可。
public class Solution {private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};private int m, n;public int longestIncreasingPath(int[][] matrix) {if (matrix.length == 0) return 0;m = matrix.length; n = matrix[0].length;int[][] cache = new int[m][n];int ans = 0;for (int i = 0; i < m; ++i)for (int j = 0; j < n; ++j)ans = Math.max(ans, dfs(matrix, i, j, cache));return ans;}private int dfs(int[][] matrix, int i, int j, int[][] cache) {if (cache[i][j] != 0) return cache[i][j];for (int[] d : dirs) {int x = i + d[0], y = j + d[1];if (0 <= x && x < m && 0 <= y && y < n && matrix[x][y] > matrix[i][j])cache[i][j] = Math.max(cache[i][j], dfs(matrix, x, y, cache));}return ++cache[i][j];}
}