[LeetCode] 329. Longest Increasing Path in a Matrix
阿新 • • 發佈:2020-07-22
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 }