首页>itarticle>[leetcode]longest increasing path in a matrix
[leetcode]longest increasing path in a matrix
admin11月 12, 20200
题目描述
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:
1 2 3 4 5
nums = [ [9,9,4], [6,6,8], [2,1,1] ]
Return 4 The longest increasing path is [1, 2, 6, 9].
Example 2:
1 2 3 4 5
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.
publicintlongestIncreasingPath(int[][] matrix){ if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return0; int row = matrix.length, col = matrix[0].length; int max = 1; int[][] cache = newint[row][col]; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ int len = dfs(matrix, i, j, row, col, cache); max = Math.max(max, len); } }
return max; }
//深度搜索从[i][j]出发的最长递增路径的长度 //cache缓存,即备忘录 publicintdfs(int[][] matrix, int i, int j, int row, int col, 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]; //matrix[x][y] <= matrix[i][j]可以避免使用visited[row][col]数组 if(x < 0 || x >= row || y < 0 || y >= col || matrix[x][y] <= matrix[i][j]) continue; int len = 1 + dfs(matrix, x, y, row, col, cache); max = Math.max(len, max); }
近期评论