329. Longest Increasing Path in a Matrix
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:
nums = [ [9,9,4], [6,6,8], [2,1,1] ]
Return 4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
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.
第一种方法,递归。很明显,时间超时,通不过。
1 class Solution { 2 public int longestIncreasingPath(int[][] matrix) { 3 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0; 4 int max = 0; 5 boolean[][] visited = new boolean[matrix.length][matrix[0].length]; 6 for (int i = 0; i < matrix.length; i++) { 7 for (int j = 0; j < matrix[0].length; j++) { 8 max = Math.max(max, helper(matrix, visited, i, j)); 9 } 10 } 11 return max; 12 } 13 14 public int helper(int[][] A, boolean[][] visited, int i, int j) { 15 visited[i][j] = true; 16 int[][] neighbors = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; 17 int max = 0; 18 for (int[] neighbor : neighbors) { 19 int row = i + neighbor[0]; 20 int col = j + neighbor[1]; 21 if (row >= 0 && row < A.length && col >= 0 && col < A[0].length && !visited[row][col] && A[row][col] > A[i][j]) { 22 max = Math.max(max, helper(A, visited, row, col)); 23 } 24 } 25 visited[i][j] = false; 26 return max + 1; 27 } 28 }
第二种方法类似第一种方法,但是我们不会每次都对同一个位置重复计算。对于一个点来讲,它的最长路径是由它周围的点决定的,你可能会认为,它周围的点也是由当前点决定的,这样就会陷入一个死循环的怪圈。其实并没有,因为我们这里有一个条件是路径上的值是递增的,所以我们一定能够找到一个点,它不比周围的值大,这样的话,整个问题就可以解决了。
1 public class Solution { 2 public int longestIncreasingPath(int[][] A) { 3 int res = 0; 4 if (A == null || A.length == 0 || A[0].length == 0) { 5 return res; 6 } 7 int[][] store = new int[A.length][A[0].length]; 8 for (int i = 0; i < A.length; i++) { 9 for (int j = 0; j < A[0].length; j++) { 10 if (store[i][j] == 0) { 11 res = Math.max(res, dfs(A, store, i, j)); 12 } 13 } 14 } 15 return res; 16 } 17 18 private int dfs(int[][] A, int[][] store, int i, int j) { 19 if (store[i][j] != 0) return store[i][j]; 20 int max = 0; 21 int[][] neighbors = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; 22 for (int[] neighbor : neighbors) { 23 int row = i + neighbor[0]; 24 int col = j + neighbor[1]; 25 if (row >= 0 && row < A.length && col >= 0 && col < A[0].length && A[row][col] > A[i][j]) { 26 max = Math.max(max, dfs(A, store, row, col)); 27 } 28 } 29 store[i][j] = max + 1; 30 return store[i][j]; 31 } 32 }