題目:
Given an integer matrix, find the length of the longest increasing path.java
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).ide
Example 1:函數
nums = [ [9,9,4], [6,6,8], [2,1,1] ]
Return 4
The longest increasing path is [1, 2, 6, 9].code
Example 2:it
nums = [ [3,4,5], [3,2,6], [2,2,1] ]
Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.io
解答:
最重要的是用cache保存每一個掃過結點的最大路徑。我開始作的時候,用全局變量記錄的max, dfs沒有返回值,這樣很容易出錯,由於任何一個用到max的環節都有可能改變max值,因此仍是在函數中定義,把當前的max直接返回計算不容易出錯。class
public class Solution { public int DFS(int[][] matrix, int i, int j, int[][] cache) { if (cache[i][j] != 0) return cache[i][j]; //改進:記錄下每個訪問過的點的最大長度,當從新訪問到這個點的時候,就不須要重複計算 int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int max = 1; for (int k = 0; k < dir.length; k++) { int x = i + dir[k][0], y = j + dir[k][1]; if (x < 0 || x > matrix.length - 1 || y < 0 || y > matrix[0].length - 1) { continue; } else { if (matrix[x][y] > matrix[i][j]) { //這裏當前結點只算長度1,而後加上dfs後子路徑的長度,比較得出最大值 int len = 1 + DFS(matrix, x, y, cache); max = Math.max(max, len); } } } cache[i][j] = max; return max; } public int longestIncreasingPath(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0; int m = matrix.length, n = matrix[0].length; int[][] cache = new int[m][n]; int max = 1; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int len = DFS(matrix, i, j, cache); max = Math.max(max, len); } } return max; } }