V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Dijkstra's Shortest Path

Single-source shortest paths on a non-negative weighted graph

From tentative to final distances

Dijkstra's algorithm stores the best distance currently known from one source to every vertex. The source starts at 0 and all other vertices start at infinity. Repeatedly choose the unsettled vertex with the smallest tentative distance, settle it, and relax each outgoing edge.

Watch relaxation change the graph

The amber ring marks the active vertex, green vertices are settled, and the small badge beside each vertex is its current distance. An edge relaxation asks whether reaching a neighbor through the active vertex is shorter than the route stored so far. The final green edges form a shortest-path tree rooted at A.

412517362A0B∞C∞D∞E∞F∞

Set the source distance to 0 and every other distance to infinity.

1function dijkstra(adj: [number, number][][], source: number, n: number): number[] {
2 const dist = Array(n).fill(Infinity);
3 dist[source] = 0;
4 const done = Array(n).fill(false);
5 for (let k = 0; k < n; k++) {
6 let u = -1;
7 for (let i = 0; i < n; i++)
8 if (!done[i] && dist[i] < Infinity && (u < 0 || dist[i] < dist[u])) u = i;
9 if (u < 0) break;
10 done[u] = true;
11 for (const [v, w] of adj[u]) {
12 if (dist[u] + w < dist[v]) {
13 dist[v] = dist[u] + w;
14 }
15 }
16 }
17 return dist;
18}
n6
k0
u (current)-
Settled-
dist[A]0
dist[B]∞
dist[C]∞
dist[D]∞
dist[E]∞
dist[F]∞
1 / 32

Why non-negative weights matter

Once the nearest unsettled vertex is chosen, non-negative edges guarantee that no later route can make it cheaper. Negative edges break that argument. With a binary heap, the usual running time is O((V + E) log V).

Typical uses include map routing, network path selection, and any state graph where each move has a non-negative cost. For negative weights, use a different shortest-path algorithm.