Skip to content

Instantly share code, notes, and snippets.

@eldilibra
Created October 24, 2014 00:21
Show Gist options
  • Save eldilibra/d49abd9c47b93f1a312f to your computer and use it in GitHub Desktop.
Save eldilibra/d49abd9c47b93f1a312f to your computer and use it in GitHub Desktop.
function Node (id) {
this.id = id;
this.friends = [];
this.equals = function equals (otherNode) {
return this.id === otherNode.id;
};
}
function shortestPath (root, dest) {
var current = root;
var visited = {};
visited[root.id] = { hops: 0, prev: null };
var valid = [];
var counter = 0;
var finalPath = [dest];
var finalPrevious;
while (!current.equals(dest)) {
current.friends.forEach(function (c) {
if (visited[c.id]) {
console.log('step #' + (++counter));
console.log('skipping', c.id, 'since it has been visited');
return;
}
console.log('step #' + (++counter));
console.log(c.id);
visited[c.id] = {
hops: visited[current.id].hops + 1,
prev: current
};
valid.push(c);
});
current = valid.shift();
}
while (!finalPath[0].equals(root)) {
finalPrevious = visited[finalPath[0].id].prev;
finalPath.unshift(finalPrevious);
}
return finalPath;
}
var you = new Node("You", 0);
var a = new Node("a");
var b = new Node("b");
var c = new Node("c");
var d = new Node("d");
var e = new Node("e");
var f = new Node("f");
d.friends.push(f);
c.friends.push(d);
b.friends.push(e);
b.friends.push(c);
a.friends.push(e);
a.friends.push(b);
you.friends.push(a);
you.friends.push(b);
you.friends.push(c);
console.log(shortestPath(you, f));
@eldilibra
Copy link
Author

Obviously, one can examine the visited structure to see the number of hops along the way, or just get the length of finalPath after returning it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment