标签:
/* * 329. Longest Increasing Path in a Matrix * 2016-7-9 by Mingyang * 其实这种类型的题目没有想象的那么难,你只需要好好的按照dfs的概念一点一点的走就好了 * 记住,每个dfs不光是void的,也可以返回一个长度 */ public static final int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; public int longestIncreasingPath(int[][] matrix) { if (matrix.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, m, n, cache); max = Math.max(max, len); } } return max; } public int dfs(int[][] matrix, int i, int j, int m, int n, int[][] cache) { if (cache[i][j] != 0) return cache[i][j]; int max = 1; for (int[] dir : dirs) { int x = i + dir[0], y = j + dir[1]; if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] <= matrix[i][j]) continue; //m,n is the boundry int len = 1 + dfs(matrix, x, y, m, n, cache); max = Math.max(max, len); } cache[i][j] = max; return max; }
329. Longest Increasing Path in a Matrix
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5657029.html