LeetCode 329. Longest Increasing Path in a Matrix
原题链接在这里: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:
1 class Solution { 2 HashMap<Integer, Integer> hm = new HashMap<>(); 3 int [][] dirs = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; 4 5 public int longestIncreasingPath(int[][] matrix) { 6 if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ 7 return 0; 8 } 9 10 int m = matrix.length; 11 int n = matrix[0].length; 12 int res = 0; 13 for(int i = 0; i<m; i++){ 14 for(int j = 0; j<n; j++){ 15 res = Math.max(res, dfs(matrix, m, n, i, j)); 16 } 17 } 18 19 return res; 20 } 21 22 private int dfs(int [][] matrix, int m, int n, int i, int j){ 23 int key = i*n+j; 24 if(hm.containsKey(key)){ 25 return hm.get(key); 26 } 27 28 int longest = 0; 29 for(int [] dir : dirs){ 30 int x = i + dir[0]; 31 int y = j + dir[1]; 32 if(x>=0 && x<m && y>=0 && y<n && matrix[x][y]>matrix[i][j]){ 33 longest = Math.max(longest, dfs(matrix, m, n, x, y)); 34 } 35 } 36 37 hm.put(key, longest+1); 38 return longest+1; 39 } 40 }