LeetCode Longest Increasing Path in a Matrix

时间:2024-01-11 14:17:02

原题链接在这里:https://leetcode.com/problems/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.

题解:

Longest increasing path could start from any grid of matrix.

We could perform DFS starting from each grid of matrix. For each of 4 neighbors, if it is within boundary and number > current grid number, continue DFS.

Could use memoization to save time. If this grid has already calcualted maximum increasing path before, simply return it.

Time Complexity: O(mn). For DFS, it could take O(mn) time. But here use memoization, each grid could be visited no more than 5 times. m = matrix.length. n = matrix[0].length.

Space: O(m*n).用了memoization.

AC Java:

 class Solution {
HashMap<Integer, Integer> hm = new HashMap<>();
int [][] dirs = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; public int longestIncreasingPath(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return 0;
} int m = matrix.length;
int n = matrix[0].length;
int res = 0;
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
res = Math.max(res, dfs(matrix, m, n, i, j));
}
} return res;
} private int dfs(int [][] matrix, int m, int n, int i, int j){
int key = i*n+j;
if(hm.containsKey(key)){
return hm.get(key);
} int longest = 0;
for(int [] dir : dirs){
int x = i + dir[0];
int y = j + dir[1];
if(x>=0 && x<m && y>=0 && y<n && matrix[x][y]>matrix[i][j]){
longest = Math.max(longest, dfs(matrix, m, n, x, y));
}
} hm.put(key, longest+1);
return longest+1;
}
}