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 are not allowed).
Example 1:
Nums = [ [9, 9,4], [6, 6,8], [2,1, 1]]
Return4
The longest increasing path is [1, 2, 6, 9] .
Example 2:
Nums = [ [3,4,5], [3,2,6], [2,2,1]
Return4
The longest increasing path is [3, 4, 5, 6] . Moving diagonally is not allowed.
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
Look for the longest incremental path and return the length.
DFS recursive traversal finds the longest path, opening a hash table to record the nodes that have been visited, improving efficiency.
1 /**2 * @param {number[][]} matrix3 * @return {number}4 */5 varLongestincreasingpath =function(matrix) {6 varDirection = [{x:-1, y:0}, {x:1, y:0}, {x:0, Y:-1}, {x:0, y:1}];7 varDictionary = {}, max = 0;8 for(vari = 0; i < matrix.length; i++)9 for(varj = 0; J < Matrix[i].length; J + +)TenMax =Math.max (max, DFS (i, j)); One returnMax; A - functiondfs (x, y) { - varCurr = dictionary[x + ' # ' +y]; the if(Curr)returnCurr; -Curr =Matrix[x][y]; - - varD, max = 0, isend =true, TMP; + for(vari = 0; i < direction.length; i++){ -D =Direction[i]; + if(Matrix[x +D.x]) { ATMP = matrix[x + d.x][y +D.y]; at if(TMP && tmp >Curr) { -max = Math.max (max, DFS (x + d.x, y +d.y)); -Isend =false; - } - } - } in -max = Isend? 1:max + 1; toDictionary[x + ' # ' + y] =Max; + returnMax; - } the}
[Leetcode] [JavaScript] Longest increasing Path in a Matrix