dfs(problem a){ if(a has been solved) then: consult the record. else//get the optimal solution of problem a. divide the problem a into several sub-problems(a1,a2,...,ak) get the solution of problem a by dfs(a1),dfs(a2),...,dfs(ak). finally write the optimal solution into record. }
public class LongestIncrementalPath { static int row;//行 static int colcumn;//列 public static void main(String[] args) { /** * [ [9,9,4], [6,6,8], [2,1,1] ] */ int[][] m = {{9,9,4},{6,6,8},{2,1,1}};//示例 int length =longestIncreasingPath(m); System.out.println("最长递增路径的长度【1】:"+length);
} public static int longestIncreasingPath(int[][] matrix) { if (matrix.length == 0) return 0; int m = matrix.length, n = matrix[0].length; int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; int[][] map = new int[m][n]; int res = 1; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { res = Math.max(res, dfs(matrix, i, j, map, dirs)); } } return res; } // dfs求以点(i,j)结尾的最长递增路径 public static int dfs(int[][] matrix, int i, int j, int[][] map, int[][] dirs) { if (map[i][j] != 0) return map[i][j]; int res = 1; for (int[] dir : dirs) { int x = i + dir[0], y = j + dir[1];
if (x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || matrix[x][y] >= matrix[i][j]) continue; // 当周围的点小于当前点才递归 res = Math.max(res, 1 + dfs(matrix, x, y, map, dirs)); } map[i][j] = res; return res; } }