[LeetCode] 329. Longest Increasing Path in a Matrix

Given an m x n integers matrix, return the length of the longest increasing path in matrix.

From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).

Example 1:

Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].

Example 2:

Input: matrix = [[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.

Example 3:

Input: matrix = [[1]]
Output: 1

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 231 - 1

矩阵中的最长递增路径。

给定一个 m x n 整数矩阵 matrix ,找出其中 最长递增路径 的长度。

对于每个单元格,你可以往上,下,左,右四个方向移动。 你 不能 在 对角线 方向上移动或移动到 边界外(即不允许环绕)。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-increasing-path-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意是给一个二维矩阵,找出最长的递增路径。例子应该很好地解释了什么叫做最长的递增路径。

这道题也是偏 flood fill 那一类的题。因为路径是连续的且只是往上下左右四个方向,所以需要再创建一个同样 size 的二维数组来记录遍历的结果,否则会超时。二维数组内每个坐标上记录的值的意思是从当前的点 (x, y) 出发能得到的最长路径是多少。

还是应用 DFS 的模板,但是在设计 dfs 函数的时候记得加一个额外的二维数组记录结果。其余的部分可参见代码。

时间O(mn)

空间O(mn) - 额外数组缓存结果

Java实现

 1 class Solution {
 2     int m;
 3     int n;
 4 
 5     public int longestIncreasingPath(int[][] matrix) {
 6         // corner case
 7         if (matrix == null || matrix.length == 0) {
 8             return 0;
 9         }
10 
11         // normal case
12         m = matrix.length;
13         n = matrix[0].length;
14         int res = 0;
15         int[][] memo = new int[m][n];
16         for (int i = 0; i < m; i++) {
17             for (int j = 0; j < n; j++) {
18                 if (memo[i][j] == 0) {
19                     res = Math.max(res, dfs(matrix, memo, i, j));
20                 }
21             }
22         }
23         return res;
24     }
25     
26     private int dfs(int[][] matrix, int[][] memo, int x, int y) {
27         int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
28         int res = 1;
29         int m = matrix.length;
30         int n = matrix[0].length;
31         // 如果已经访问过则返回记录的value
32         if (memo[x][y] > 0) {
33             return memo[x][y];
34         }
35         for (int[] dir : dirs) {
36             int nextX = x + dir[0];
37             int nextY = y + dir[1];
38             // 越界就continue
39             // 如果不是更大的数字也continue
40             if (nextX < 0 || nextY < 0 || nextX >= m || nextY >= n || matrix[nextX][nextY] <= matrix[x][y]) {
41                 continue;
42             }
43             // 记住路径长度要+1
44             res = Math.max(res, dfs(matrix, memo, nextX, nextY) + 1);
45         }
46         memo[x][y] = res;
47         return res;
48     }
49 }

 

flood fill题型总结

LeetCode 题目总结

posted @ 2020-07-22 15:45  CNoodle  阅读(314)  评论(0编辑  收藏  举报