Skip to content
DSA in JavaScript
← All patterns

Weighted Shortest Path

0/8 solved

What it is

Find the cheapest route in a graph where edges have different costs, by always expanding the closest unvisited node first.

Used for

Road networks, network delay, cheapest flights, minimum effort paths.
node
A
B
C
D
cost
0
∞
∞
∞

Step 1 of 6

Goal: the cheapest route from A to every place when roads have different costs: A→B 4, A→C 1, C→B 2, B→D 1. Keep a table of the best known cost to each place: 0 for A, unknown for the rest.

You see

  • Cheapest route with edge weights
  • Network delay or cheapest flights
  • Negative edges (Bellman-Ford)

Learn it in

Prim's AlgorithmDijkstra's AlgorithmBellman–Ford AlgorithmFloyd–Warshall Algorithm

Template

// Dijkstra: expand the closest unvisited node using a priority queue.// See the Dijkstra topic for the full implementation on top of PriorityQueue.

Practice problems