Hard Graphs

Shortest Path (Dijkstra)

Computes the shortest distance from node 0 to every other node in a weighted graph using Dijkstra's algorithm. Repeatedly picks the unvisited node with the smallest known distance, marks it settled, then relaxes every edge leaving it — lowering a neighbor's tentative distance whenever a shorter path is found through the current node — until every reachable node has its final, minimum distance. Receives the graph as a square adjacency matrix, where a positive value at row i, column j is the weight of an edge between nodes i and j (0 or negative means no edge; weights must be non-negative for the algorithm to be correct). Returns the shortest distance from node 0 to every node, using -1 for a node that cannot be reached at all.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References