Created
February 5, 2016 13:22
-
-
Save gulbanana/75e8d3ab37baa313761b to your computer and use it in GitHub Desktop.
This file contains 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
function shortest(graph) | |
{ | |
var paths = []; | |
var counts = graph.map(_ => 0); | |
for (var startNode of graph.keys()) | |
{ | |
paths[startNode] = []; | |
var visited = [startNode]; | |
function visit(node, path) | |
{ | |
if (path.length) | |
{ | |
visited.push(node); | |
if (!paths[node] || !paths[node][startNode]) // record this path unless it's the reverse of an existing one | |
{ | |
paths[startNode][node] = path; | |
for (var n of path.slice(0, path.length-1)) | |
{ | |
counts[n]++; | |
} | |
} | |
} | |
for (var nextNode of graph[node]) | |
{ | |
if (visited.indexOf(nextNode) == -1) | |
{ | |
visit(nextNode, path.concat([nextNode])); | |
} | |
} | |
} | |
visit(startNode, []); | |
} | |
var sortedCounts = counts.slice().sort((a, b) => b - a); | |
return "node " + counts.indexOf(sortedCounts[0]) + " is on " + sortedCounts[0] + " paths"; | |
} | |
var test = [[1,4], [2,3], [1], [1], [0,5], [4]]; | |
var result = shortest(test); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment