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.
矩阵中的最长递增路径。题意是给一个二维矩阵,找出最长的递增路径。例子应该很好地解释了什么叫做最长的递增路径。
这道题也是偏flood fill那一类的题,同时因为是找最长路径,所以用DFS做更好。因为路径是连续的且只是往上下左右四个方向,所以需要再创建一个同样size的二维数组来记录遍历的结果,这样就不需要遍历整个input数组了,因为input数组中比如数字为9的坐标,实际是没什么扫描的意义的,因为数字非常大了,而他的邻居搞不好都比他本身小。具体做法还是应用DFS的模板,但是在设计dfs函数的时候记得加一个额外的二维数组记录结果,也加一个prev值,用来和当前坐标上的值作比较。其余的部分可参见代码。
时间O(mn)
空间O(mn) - 额外数组缓存结果
Java实现
1 class Solution { 2 public int longestIncreasingPath(int[][] matrix) { 3 if (matrix == null || matrix.length == 0) { 4 return 0; 5 } 6 int rows = matrix.length; 7 int cols = matrix[0].length; 8 int[][] dp = new int[rows][cols]; 9 int res = 0; 10 for (int i = 0; i < rows; i++) { 11 for (int j = 0; j < cols; j++) { 12 if (dp[i][j] == 0) { 13 dfs(matrix, i, j, dp, Integer.MIN_VALUE); 14 res = Math.max(res, dp[i][j]); 15 } 16 } 17 } 18 return res; 19 } 20 21 private int dfs(int[][] matrix, int row, int col, int[][] dp, int prev) { 22 if (row > matrix.length - 1 || row < 0 || col > matrix[0].length - 1 || col < 0 || matrix[row][col] <= prev) { 23 return 0; 24 } 25 if (dp[row][col] != 0) { 26 return dp[row][col]; 27 } 28 int left = dfs(matrix, row, col - 1, dp, matrix[row][col]); 29 int right = dfs(matrix, row, col + 1, dp, matrix[row][col]); 30 int up = dfs(matrix, row - 1, col, dp, matrix[row][col]); 31 int down = dfs(matrix, row + 1, col, dp, matrix[row][col]); 32 dp[row][col] = Math.max(left, Math.max(right, Math.max(up, down))) + 1; 33 return dp[row][col]; 34 } 35 }