Longest Increasing Path in a Matrix

来源:互联网 发布:mac口红whirl 编辑:程序博客网 时间:2024/06/09 21:38

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.

第一种解法:通过递归,但是复杂度太高。

public int longestIncreasingPath(int[][] matrix) {int tempMax = 0;for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[0].length; j++) {boolean[][] visited = new boolean[matrix.length][matrix[0].length];int temp = longestIncreasingPathHelper(matrix, visited, i, j, matrix[i][j] - 1);if (temp > tempMax) {tempMax = temp;}}}return tempMax;}public static int longestIncreasingPathHelper(int[][] matrix, boolean[][] visited, int i, int j, int prev) {if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length)return 0;if (visited[i][j] == true|| matrix[i][j] <= prev)visited[i][j] = true;int max1 = longestIncreasingPathHelper(matrix, visited, i + 1, j, matrix[i][j]);int max2 = longestIncreasingPathHelper(matrix, visited, i - 1, j, matrix[i][j]);int max3 = longestIncreasingPathHelper(matrix, visited, i, j + 1, matrix[i][j]);int max4 = longestIncreasingPathHelper(matrix, visited, i, j - 1, matrix[i][j]);visited[i][j] = false;return max(max1, max2, max3, max4) + 1;}public static int max(int a, int b, int c, int d) {return max(max(a, b), max(c, d));}public static int max(int a, int b) {if (a > b)return a;return b;}

第二种方法类似第一种方法,但是我们不会每次都对同一个位置重复计算。对于一个点来讲,它的最长路径是由它周围的点决定的,你可能会认为,它周围的点也是由当前点决定的,这样就会陷入一个死循环的怪圈。其实并没有,因为我们这里有一个条件是路径上的值是递增的,所以我们一定能够找到一个点,它不比周围的值大,这样的话,整个问题就可以解决了。

public int <span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">longestIncreasingPath </span><span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">(int[][] A) {</span>int res = 0;if (A == null || A.length == 0 || A[0].length == 0) {return res;}int[][] store = new int[A.length][A[0].length];for (int i = 0; i < A.length; i++) {for (int j = 0; j < A[0].length; j++) {if (store[i][j] == 0) {res = Math.max(res, dfs(A, store, i, j));}}}return res;}private static int dfs(int[][] a, int[][] store, int i, int j) {if (store[i][j] != 0) {return store[i][j];}int left = 0, right = 0, up = 0, down = 0;if (j + 1 < a[0].length && a[i][j + 1] > a[i][j]) {right = dfs(a, store, i, j + 1);}if (j > 0 && a[i][j - 1] > a[i][j]) {left = dfs(a, store, i, j - 1);}if (i + 1 < a.length && a[i + 1][j] > a[i][j]) {down = dfs(a, store, i + 1, j);}if (i > 0 && a[i - 1][j] > a[i][j]) {up = dfs(a, store, i - 1, j);}store[i][j] = Math.max(Math.max(up, down), Math.max(left, right)) + 1;return store[i][j];}


0 0