Leetcode: Longest Increasing Path in a Matrix

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode: 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:

nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]
Return 4
The longest increasing path is [1, 2, 6, 9].

Example 2:

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.

DFS + DP:

use a two dimensional matrix dp[i][j] to store the length of the longest increasing path starting at matrix[i][j]

transferring function is: dp[i][j] = max(dp[i][j], dp[x][y] + 1), where dp[x][y] is its neighbor with matrix[x][y] > matrix[i][j]

 1 public class Solution {
 2     int[][] dp;
 3     int[][] directions = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};
 4     int m;
 5     int n;
 6     int[][] mx;
 7     public int longestIncreasingPath(int[][] matrix) {
 8         if (matrix==null || matrix.length==0 || matrix[0].length==0) return 0;
 9         m = matrix.length;
10         n = matrix[0].length;
11         dp = new int[m][n];
12         mx = matrix;
13         int result = 0;
14         for (int i=0; i<m; i++) {
15             for (int j=0; j<n; j++) {
16                 dp[i][j] = Integer.MIN_VALUE;
17             }
18         }
19         for (int i=0; i<m; i++) {
20             for (int j=0; j<n; j++) {
21                 result = Math.max(result, DFS(i,j));
22             }
23         }
24         return result;
25     }
26     
27     public int DFS(int i, int j) {
28         if (dp[i][j] != Integer.MIN_VALUE) return dp[i][j];
29         dp[i][j] = 1;
30         for (int[] dir : directions) {
31             int x = i + dir[0];
32             int y = j + dir[1];
33             if (x<0 || y<0 || x>=m || y>=n || mx[x][y]<=mx[i][j]) continue;
34             dp[i][j] = Math.max(dp[i][j], DFS(x,y)+1);
35         }
36         return dp[i][j];
37     }
38 }

 

以上是关于Leetcode: Longest Increasing Path in a Matrix的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode409. Longest Palindrome

leetcode:longest-increasing

[Leetcode]Longest Palindromic Substring

leetcode longest consecutive sequence

LeetCode Longest Increasing Subsequence

#Leetcode# 14. Longest Common Prefix