djkstra's algorithm in javascript

Dijkstra's algorithm is a popular algorithm for finding the shortest path between two nodes in a graph. Here's an implementation of Dijkstra's algorithm in Javascript:

index.tsx
function dijkstra(graph, startNode, endNode) {
  // Initialize distances with infinity except for the startNode which is 0
  let distances = {};
  for (let node in graph) {
    distances[node] = Infinity
  }
  distances[startNode] = 0;
  
  // Set up a queue for unvisited nodes
  let unvisitedNodes = new Set(Object.keys(graph));
  
  // Create an object to keep track of the shortest path
  let shortestPath = {};
  while (unvisitedNodes.size !== 0) {
    let closestNode = null;
    // Find the closest unvisitedNode to the startNode
    for (let node of unvisitedNodes) {
      if (closestNode === null || distances[node] < distances[closestNode]) {
        closestNode = node;
      }
    }
    
    // Find the distance from the closestNode to its neighbors
    for (let neighbor in graph[closestNode]) {
      let distance = graph[closestNode][neighbor];
      let newPath = distances[closestNode] + distance;
      if (newPath < distances[neighbor]) {
        distances[neighbor] = newPath;
        shortestPath[neighbor] = closestNode;
      }
    }
    
    // Remove the closestNode from the unvisitedNodes set since we have visited it
    unvisitedNodes.delete(closestNode);
  }
  
  // If no path exists, return null
  if (distances[endNode] === Infinity) {
    return null;
  }
  
  // Trace the path back from the endNode to the startNode
  let path = [endNode];
  let lastNode = endNode;
  while (lastNode !== startNode) {
    path.unshift(shortestPath[lastNode]);
    lastNode = shortestPath[lastNode];
  }
  
  return { distance: distances[endNode], path: path };
}
1584 chars
52 lines

The graph parameter of the dijkstra function should be an object representing the graph. Each key in the graph object represents a node in the graph, with the value being an object with keys being the node's neighbors and values being the distances to those neighbors.

For example, a graph with nodes A, B, and C with distances (A,B) = 3, (A,C) = 4, and (B,C) = 1 would be represented as:

index.tsx
let graph = {
  "A": { "B": 3, "C": 4 },
  "B": { "C": 1 },
  "C": {}
};
73 chars
6 lines

To use the dijkstra function, pass in the graph object, the starting node, and the ending node:

index.tsx
let shortestPath = dijkstra(graph, "A", "C");
console.log(shortestPath); // { distance: 4, path: ["A", "B", "C"] }
115 chars
3 lines

This code will output the shortest distance between nodes A and C and the shortest path to get from node A to node C.

gistlibby LogSnag