Created
April 13, 2020 03:57
-
-
Save RP-3/fd644b8f4b5c66c56a9cf9041a20c95a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const longestPath = (adjList) => { | |
const graph = {}; | |
adjList.forEach(([from, to]) => { | |
if(!graph[from]) graph[from] = new Set(); | |
graph[from].add(to); | |
}); | |
const memo = {}; // node -> longestPathLength starting at node | |
let result = 0; | |
for(let start in graph){ | |
if(!memo.hasOwnProperty(start)) memo[start] = _longestPath(start); | |
result = Math.max(result, memo[start]); | |
} | |
return result; | |
function _longestPath(startNode){ | |
if(memo.hasOwnProperty(startNode)) return memo[startNode]; | |
if(!graph[startNode]) return 0; | |
let maxPathLength = 0; | |
for(let adj of graph[startNode]){ | |
maxPathLength = Math.max(maxPathLength, 1 + _longestPath(adj)); | |
} | |
return memo[startNode] = maxPathLength; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment