[LeetCode][JavaScript]Longest Increasing Path in a Matrix

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode][JavaScript]Longest Increasing Path in a Matrix相关的知识,希望对你有一定的参考价值。

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.

https://leetcode.com/problems/longest-increasing-path-in-a-matrix/

 

 


 

 

寻找最长的递增路径,返回长度。

DFS递归遍历找出最长的路径,开一个哈希表记录已经访问过的节点,提高效率。

 

 1 /**
 2  * @param {number[][]} matrix
 3  * @return {number}
 4  */
 5 var longestIncreasingPath = function(matrix) {
 6     var direction = [{x : -1, y : 0}, {x : 1, y : 0}, {x : 0, y : -1}, {x : 0, y : 1}];
 7     var dictionary = {}, max = 0;
 8     for(var i = 0; i < matrix.length; i++)
 9         for(var j = 0; j < matrix[i].length; j++)
10             max = Math.max(max, dfs(i, j));
11     return max;
12     
13     function dfs(x, y){
14         var curr = dictionary[x + ‘#‘ + y];
15         if(curr) return curr;
16         curr = matrix[x][y];
17         
18         var d, max = 0, isEnd = true, tmp;
19         for(var i = 0; i < direction.length; i++){
20             d = direction[i];
21             if(matrix[x + d.x]){
22                 tmp = matrix[x + d.x][y + d.y];
23                 if(tmp && tmp > curr){
24                     max = Math.max(max, dfs(x + d.x, y + d.y));
25                     isEnd = false;
26                 }
27             }
28         }
29         
30         max = isEnd ? 1 : max + 1;
31         dictionary[x + ‘#‘ + y] = max;
32         return max;
33     }
34 }

 

 

 

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

LeetCode 187. Repeated DNA Sequences 20170706 第三十次作业

[LeetCode] 187. Repeated DNA Sequences 求重复的DNA序列

LeetCode69.x的平方根

对 lon\lat 点的排序列表,从最近的开始

组 lat/lon ,如果它们出现在边界框内

具有多个参数的 pyspark udf