Dijkstra's Algorithm

Languages

Given a weighted directed graph represented as an adjacency list (graph) and a starting node (source), implement Dijkstra's algorithm to find the shortest path distances from source to all other nodes in the graph. The graph contains nodes and weighted edges.

Input

  • graph: An object representing the adjacency list of the graph. Each key is a node identifier (e.g. 'A', 'B'), and its value is another object that maps each neighboring node to the non-negative weight of the edge connecting them.
  • source: The identifier of the starting node from which to calculate shortest paths.

Output

  • An object where keys are node identifiers and values represent the shortest distance from source to that node. Nodes that are unreachable from source should have their distance set to Infinity (use the built-in Infinity constant). Return an empty object when graph is empty.

Examples

const graph1 = {
A: { B: 1, C: 4 },
B: { E: 3, F: 2 },
C: { G: 2 },
D: { C: 3, J: 5 },
E: { D: 2 },
F: {},
G: { H: 1 },
H: { F: 4, J: 3 },
I: {},
J: {},
};
dijkstra(graph1, 'A'); // Returns distances: { A: 0, B: 1, C: 4, D: 6, E: 4, F: 3, G: 6, H: 7, I: Infinity, J: 10 }
const graph2 = {
A: { B: 2, C: 5 },
B: { D: 1, E: 4 },
C: { F: 3, G: 2 },
D: {},
E: {},
F: {},
G: {},
};
dijkstra(graph2, 'A'); // Returns distances: { A: 0, B: 2, C: 5, D: 3, E: 6, F: 8, G: 7 }

Constraints

  • 1 <= Number of nodes <= 1000
  • 0 <= Edge weight <= 10000
  • The graph may contain cycles
  • The graph may be disconnected

Hints

New

Loading editor

    Dijkstra's Algorithm | Algorithms Interview Questions with Solutions