[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 }
原文地址:https://www.cnblogs.com/Liok3187/p/5181130.html