Created
June 22, 2018 05:09
-
-
Save linfongi/9adeceb176a4187668aad36668eed6b5 to your computer and use it in GitHub Desktop.
code.js
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 shortestPathLength(graph) { | |
const dp = [...Array(graph.length)].map(r => Array(1<<(graph.length+1)).fill(Math.MAX_VALUE)); | |
const queue = []; | |
for (let v = 0; v < graph.length; v++) { | |
dp[v][1<<v] = 0; | |
queue.unshift([v, 1<<v]); | |
} | |
while (queue.length) { | |
let curr = queue.pop(); | |
if (curr[1] === (1<<graph.length) - 1) return dp[curr[0]][curr[1]]; | |
for (let next of graph[curr[0]]) { | |
let nextBitMask = curr[1] | (1<<next); | |
if (dp[next][nextBitMask] === Math.MAX_VALUE) { | |
dp[next][nextBitMask] = 1 + dp[curr[0]][curr[1]]; | |
queue.unshift([next, nextBitMask]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment