2019.9.29 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
github:https://github.com/ChopinXBP/LeetCode-Babel
这一题乍一看好像直接上DFS,但是很容易会超时。可以考虑复用已经计算过的结果,用记忆化DFS的方法做(也是效率最高的方法)。
另外还有一种比较巧妙的方法:动态规划+拓扑排序。
1.在matrix外围加上一层初值为0(或最小值)的数组,方便运算。
2.计算矩阵中每一点的出度并存入outdegree数组,出度为周围大于该元素的点数,出度为0代表局部最大。
3.将所有出度为0(局部最大)的元素标记为叶子元素存储到leaves中。
4.逆向思维,每次迭代所有叶子元素,最大长度+1,并且将每一叶子结点相邻的比叶子结点小的元素的出度-1,若其出度为0,则作为新的叶子结点继续迭代,直至没有叶子结点。
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).
给定一个整数矩阵,找出最长递增路径的长度。
对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
示例 1:
输入: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
输出: 4
解释: 最长递增路径为 [1, 2, 6, 9]。
示例 2:
输入: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
输出: 4
解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。
import java.util.ArrayList;
/**
*
* 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).
* 给定一个整数矩阵,找出最长递增路径的长度。
* 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
*
*/
public class LongestIncreasingPathInAMatrix {
//记忆化递归
private final int[][] directions = {
{
0, 1}, {
1, 0}, {
0, -1}, {
-1, 0}};
public int longestIncreasingPath(int[][] matrix) {
if(matrix.length == 0){
return 0;
}
int row = matrix.length;
int col = matrix[0].length;
int[][] cache = new int