Dijkstra's shortest path algorithm ================================== Find the shortest path from a source node to every other node Variables --------- C is an adjacency list (array of lists of edges) T is a table which records the shortest path found so far. It is a one-dimensional array of records/structs: T[v].dist is distance T[v].visited bool, says whether it's been a 'v' variable yet T[v].path saves the previous node of the shortest path Algorithm --------- Initialization: T[k].dist set to INFINITY except the source is set to zero (all k) T[k].visited set to false (all k) T[k].path set to zero (all k) for i = 1 to (#vertices-1) { // Find the not yet visited node with the minimum distance // This is a node, the v node, that hasn't been gone thru yet find v mark v as visited for each w adjacent to v { if (w is not visited) // Adjust the shortest distance from source to w // If going through v is shorter, set .path to v T[w].dist = min(T[w].dist, T[v].dist + edge cost v-->w } } Setting path in the above algorithm: When it is better to go through v, i.e., when T[v].dist + edge cost v-->w replaces T[w].dist as the shortest distance, set T[w].path to v. Explanation ----------- The critical line of code is T[w].dist = min(T[w].dist, T[v].dist + edge cost from v to w This is asking: should you go through v? Or verbosely, is it better to stick with the shortest distance known so far from the source to w (which is T[w].dist), or is it shorter to go through v (which is (T[v].dist + edge cost from v to w, the distance from the source to v plus the edge cost from v to w) )? Visually, you're always trying to get from the "source" node to the "w" node. Should you go through the "v" node, or not, to give the shortest distance? T[w].dist source ------------> w \ ^ \ / T[v].dist \ / edge cost v-->w \ / \ / \ / \ / > / v