LeetcodeLongest Increasing Path in a Matrix

Posted wuezs

tags:

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


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

LeetcodeLongest Palindromic Substring

LeetCodeLongest Substring Without Repeating Characters

LeetCodeLongest Common Prefix

LeetcodeLongest Substring Without Repeating Characters

LeetCodeLongest Substring Without Repeating Characters 解题报告

LeetcodeLongest Increasing Path in a Matrix