题目地址: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:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
//解题思路:遍历图,利用DFS进行每一个节点的前后左右判断是否满足条件,将最大的点赋值全局变量;其中visited数组是起到缓存的作用,以免重复查询,这点借鉴了此答案。
class Solution {
int count=0;
public int longestIncreasingPath(int[][] matrix) {
int xLen = matrix.length;
int yLen = 0;
if (xLen != 0) {
yLen = matrix[0].length;
}
int[][] visited = new int[xLen][yLen];
for (int i = 0; i < xLen; i++) {
for (int k = 0; k < yLen; k++) {
if (visited[i][k] > 0) {
if(visited[i][k] > count){
count = visited[i][k];
}
continue;
}
DFS(i, k, matrix, visited, -1);
}
}
return count;
}
private int DFS(int x, int y, int[][] matrix, int[][] visited, int pre) {
if (x < 0 || y < 0 || y >= matrix[0].length || x >= matrix.length) {
return 0;
}
if (matrix[x][y] <= pre) {
return 0;
}
if (visited[x][y] > 0) {
return visited[x][y];
}
int max1 = Math.max(DFS(x, y + 1, matrix, visited, matrix[x][y]), DFS(x + 1, y, matrix, visited, matrix[x][y]));
int max2 = Math.max(DFS(x, y - 1, matrix, visited, matrix[x][y]), DFS(x - 1, y, matrix, visited, matrix[x][y]));
int max = Math.max(max1, max2) + 1;
count=Math.max(max,count);
visited[x][y] = max;
return max;
}
}