• [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 }
  • 相关阅读:
    常用函数集锦
    HDU1212加深下对取模运算的理解
    HDU1022 queue和vector模拟
    设计模式原则
    3.6html学习笔记之样式选择
    poj 1274(二分图最大匹配)
    poj 1469(二分图最大匹配)
    poj 3692(二分图匹配--最大独立集)
    Codeforces Round #230 (Div. 1) 解题报告
    Codeforces Rockethon 2014 解题报告
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5181130.html
Copyright © 2020-2023  润新知