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,4],
[,6,8],
[,,1]
]

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

Example 2:

nums = [
[,,5],
[3,2,6],
[2,2,1]
]

Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

解法:

  这道题给我们一个二维数组,让我们求矩阵中最长的递增路径,规定我们只能上下左右行走,不能走斜线或者是超过了边界。那么这道题的解法要用递归和DP来解,用DP的原因是为了提高效率,避免重复运算。我们需要维护一个二维动态数组dp,其中dp[i][j]表示数组中以(i,j)为起点的最长递增路径的长度,初始将dp数组都赋为0,当我们用递归调用时,遇到某个位置(x, y), 如果dp[x][y]不为0的话,我们直接返回dp[x][y]即可,不需要重复计算。我们需要以数组中每个位置都为起点调用递归来做,比较找出最大值。在以一个位置为起点用深度优先搜索DFS时,对其四个相邻位置进行判断,如果相邻位置的值大于上一个位置,则对相邻位置继续调用递归,并更新一个最大值,搜素完成后返回即可,参见代码如下:

public class Solution {
public int longestIncreasingPath(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return 0;
} int m = matrix.length, n = matrix[0].length;
int res = 0;
int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res = Math.max(res, findLongestPath(matrix, dp, i, j));
}
}
return res;
} public int findLongestPath(int[][] matrix, int[][] dp, int i, int j) {
dp[i][j] = 1;
int[][] next = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int k = 0; k < next.length; k++) {
int ni = i + next[k][0];
int nj = j + next[k][1];
if (ni >= 0 && ni < dp.length && nj >= 0 && nj < dp[0].length && matrix[ni][nj] > matrix[i][j]) {
if (dp[ni][nj] != 0) {
dp[i][j] = Math.max(dp[i][j], dp[ni][nj] + 1);
} else {
dp[i][j] = Math.max(dp[i][j], findLongestPath(matrix, dp, ni, nj) + 1);
}
}
}
return dp[i][j];
}
}

最新文章

  1. MySQL误操作后如何快速恢复数据
  2. Linux0.11内核--进程调度分析之2.调度
  3. css 浮动
  4. 响应式web设计读书笔记
  5. 教程-delphi的开源json库:superobject,用法简介
  6. HDOJ(HDU) 1673 Optimal Parking
  7. Maven引入hadoop依赖包出错解决办法
  8. Spring Boot快速入门
  9. 结对编程1----基于java的四则运算生成器
  10. java做图片点击文字验证码
  11. [置顶]ABP框架系列总目录(持续更新)
  12. 技巧:Vim 的纵向编辑模式【转】
  13. MyBatis通用Mapper技巧
  14. TYPE_SCROLL_INSENSITIVE is not compatible with CONCUR_UPDATABLE
  15. HDU1042 N!(大数问题,万进制)
  16. https://leetcode-cn.com/
  17. C# 多线程编程第一步——理解多线程
  18. web第一章(html)
  19. python的os和sys模块
  20. git 四个基本对象、分支、三个存储区、reset-revert-变基、cherry-pick

热门文章

  1. Oracle Form Builder
  2. “吃神么,买神么”的第一个Sprint计划(第六天)
  3. 结对项目作业GUI
  4. Ubuntu16.04 下虚拟环境的创建与使用
  5. Java基本程序设计结构
  6. 第四周PSP&amp;进度条
  7. PAT 1053 住房空置率
  8. Robot Framework 教程 (4) - 自定义Library
  9. scrapy 直接在编辑器运行
  10. [转帖]通俗解释 AWS 云服务每个组件的作用