Skip to content

Instantly share code, notes, and snippets.

@tternquist
Last active November 12, 2021 21:14
Show Gist options
  • Save tternquist/27f8fc122555dc8883fc to your computer and use it in GitHub Desktop.
Save tternquist/27f8fc122555dc8883fc to your computer and use it in GitHub Desktop.
Shortest Path (Javascript)
function shortestPath(adjList, v, goal) {
var visited = []
var queue = [];
var shortestDistance = {};
var distance = {}
var adjListKeys = Object.keys(adjList);
for (var i = 0; i < adjListKeys.length; i++) {
var node = adjListKeys[i];
if (node !== v.toString()) {
shortestDistance[node] = -1;
} else shortestDistance[node] = 0;
}
var precedingNodes = {};
visited.push(v);
queue.push(v);
while (queue.length != 0) {
var i = queue.shift();
//process
if (shortestDistance[i] == -1) {
shortestDistance[i] = (1 + shortestDistance[precedingNodes[i]])
}
for (var j = 0; j < adjList[i].length; j++) {
if (visited.indexOf(adjList[i][j]) == -1) {
queue.push(adjList[i][j]);
visited.push(adjList[i][j])
precedingNodes[adjList[i][j]] = i
}
}
}
var current = goal;
var path = [];
while (true) {
path.push(current);
if (precedingNodes[current] == v.toString()) {
path.push(precedingNodes[current]);
break;
};
current = precedingNodes[current];
}
return path;
}
var adjList = {
1: [2, 5],
2: [3, 4],
3: [2, 1],
4: [2, 5],
5: [4, 1]
};
shortestPath(adjList, 1, 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment