Here's what I got:
Code:
// Javascript
function mknode(label, adjacent) {
return { label: label, adjacent: adjacent, baconNumber: -1 };
}
var angelinaJolie = mknode('Angelina Jolie', []),
bradPitt = mknode('Brad Pitt', []),
kevinBacon = mknode('Kevin Bacon', []),
junoTemple = mknode('Juno Temple', []),
billPaxton = mknode('Bill Paxton', []),
tomHanks = mknode('Tom Hanks', []),
noMoviesActor = mknode('No Movies Actor', []);
angelinaJolie.adjacent.push(bradPitt); // Mr and Mrs Smith
angelinaJolie.adjacent.push(junoTemple); // Malificent
bradPitt.adjacent.push(angelinaJolie); // Mr and Mrs Smith
bradPitt.adjacent.push(kevinBacon); // Beyond All Boundaries
kevinBacon.adjacent.push(bradPitt); // Beyond All Boundaries
kevinBacon.adjacent.push(junoTemple); // Black Mass
kevinBacon.adjacent.push(tomHanks); // Apollo 13
kevinBacon.adjacent.push(billPaxton); // Apollo 13
junoTemple.adjacent.push(kevinBacon); // Black Mass
junoTemple.adjacent.push(angelinaJolie); // Malificent
billPaxton.adjacent.push(kevinBacon); // Apollo 13
billPaxton.adjacent.push(tomHanks); // Apollo 13
tomHanks.adjacent.push(kevinBacon); // Apollo 13
tomHanks.adjacent.push(billPaxton); // Apollo 13
function baconNumber(actor) {
var currentBaconNumber = 0,
queue = [],
v = null;
if (actor.baconNumber !== -1) {
return actor.baconNumber;
}
function enqueueIf(v) {
if (v.baconNumber === -1) {
v.baconNumber = currentBaconNumber;
queue.push(v);
}
}
enqueueIf(kevinBacon);
while (queue.length) {
v = queue.shift();
if (v === actor) {
return v.baconNumber;
}
currentBaconNumber = v.baconNumber + 1;
v.adjacent.forEach(enqueueIf);
}
return -1;
}
console.log(baconNumber(junoTemple));
console.log(baconNumber(bradPitt));
console.log(baconNumber(billPaxton));
console.log(baconNumber(kevinBacon));
console.log(baconNumber(tomHanks));
console.log(baconNumber(noMoviesActor));
console.log(baconNumber(angelinaJolie));
Unlike the book's solution, It doesn't traverse the entire graph first; it does return the bacon number of the actor in constant time if it happened to calculate it during a previous invocation.