Ad
Algorithms
Logic

Based on the pseudocode at: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

Please check the test cases for an example input.

function dijkstra(numberOfVertices, edges, source, target) {
  if (target >= numberOfVertices) throw new Error('target outside available vertices');
  if (source < 0 || numberOfVertices === 0) throw new Error('source outside available vertices');

  const dist = {};
  const prev = {};
  const q = [];
  
  for (let v = 0; v < numberOfVertices; v++) {
    dist[v] = Infinity;
    prev[v] = null;
    q.push(v);
  }
  dist[source] = 0;
  
  while (q.length) {
    // Node with the least distance will be selected first
    const u = q.reduce((minV, v) => dist[v] < dist[minV] ? v : minV );
    
    if (u === target) break;
    
    // Remove u from q
    q.splice(q.indexOf(u), 1);
    
    (edges[u] || [])
      .forEach(edge => {
        const alt = dist[u] + edge.cost;
        if (alt < dist[edge.to]) {
          dist[edge.to] = alt;
          prev[edge.to] = u;
        }
      });
  }

  if (dist[target] === Infinity) return null;
  
  const s = [];
  let u = target;
  while (prev[u] !== null) {
    s.unshift(u);
    u = prev[u];
  }
  s.unshift(u);
  return s;
}
function sum(arr) {
  return arr.reduce((sum, elem) => sum + elem, 0);
}