【Leetcode】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:

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.

思路:

本题实质是用dsp搜索最长路径。不过没必要对图中每个节点都用dsp求一遍最长路径,参考拓扑排序只从入度为0的节点开始dsp,这样做oj判断超时,那就再优化一下,用空间换时间,在dsp过程中记忆每个节点作为起点的最长路径的长度。

具体步骤为

1.根据矩阵构建邻接表,并记录和更新节点的入度。构建邻接表时,要注意满足题意即:当某节点小于上下左右节点才有一条相应路径。

2.dsp搜索,搜索入口为入度为0的结点。

构建邻接表时间复杂度为O(n^2),空间复杂度为O(n^2)。

算法:

	HashMap<Integer, List<Integer>> maps = new HashMap<Integer, List<Integer>>();// 有向图的邻接表
	int lens[];// 记住每个节点作为起点的最大长度

	public int longestIncreasingPath(int[][] matrix) {
		if (matrix.length == 0)
			return 0;
		
		int rows = matrix.length, cols = matrix[0].length;
		int[] digree = new int[rows * cols];// 入度
		lens = new int[rows * cols];
		
		// 初始化邻接表
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				List<Integer> neibors = new LinkedList<Integer>();
				if (i - 1 >= 0 && matrix[i - 1][j] > matrix[i][j]) {// 上
					neibors.add((i - 1) * cols + j);
					digree[(i - 1) * cols + j]++;
				}
				if (i + 1 < rows && matrix[i + 1][j] > matrix[i][j]) {// 下
					neibors.add((i + 1) * cols + j);
					digree[(i + 1) * cols + j]++;
				}
				if (j - 1 >= 0 && matrix[i][j - 1] > matrix[i][j]) {// 左
					neibors.add(i * cols + (j - 1));
					digree[i * cols + (j - 1)]++;
				}
				if (j + 1 < cols && matrix[i][j + 1] > matrix[i][j]) {// 右
					neibors.add(i * cols + (j + 1));
					digree[i * cols + (j + 1)]++;
				}
				maps.put(i * cols + j, neibors);
			}

		}
		int max = 0;
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				if (digree[i * cols + j] == 0) {//入度为0的节点为搜索入口
					int len = dsp(i * cols + j, 0);
					max = Math.max(max, len);
				}
			}
		}
		return max;
	}

	public int dsp(int s, int depth) {
		if (lens[s] != 0)
			return lens[s];

		List<Integer> neibors = maps.get(s);
		int max = 0;
		for (int n : neibors) {
			lens[n] = dsp(n, depth++);
			max = Math.max(max, lens[n]);
		}
		return max + 1;
	}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值