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.tsx1584 chars52 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.tsx73 chars6 lines
To use the dijkstra
function, pass in the graph object, the starting node, and the ending node:
index.tsx115 chars3 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