Skip to content

Instantly share code, notes, and snippets.

@linfongi
Created June 22, 2018 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linfongi/9adeceb176a4187668aad36668eed6b5 to your computer and use it in GitHub Desktop.
Save linfongi/9adeceb176a4187668aad36668eed6b5 to your computer and use it in GitHub Desktop.
code.js
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