Floyd can find the shortest distance between any two points, and the code is relatively simple. It is still very efficient for sparse graphs, but the time complexity is high due to the three for loops, not suitable for dense graphs.
Floyd algorithm template (Lite version ):
Void Floyd () {int Dist [maxn] [maxn]; // The shortest distance from Dist storage I to J for (int K = 1; k <= N; k ++) for (INT I = 1; I <= N; I ++) for (Int J = 1; j <= N; j ++) if (Dist [I] [k] + dist [k] [J] <Dist [I] [J]) dist [I] [J] = DIST [I] [k] + dist [k] [J]; // continuously update the Shortest Path}
Record Shortest Path template:
Void Floyd () {for (INT I = 1; I <= N; I ++) for (Int J = 1; j <= N; j ++) {Dist [I] [J] = map [I] [J], path [I] [J] = 0 ;}for (int K = 1; k <= N; k ++) for (INT I = 1; I <= N; I ++) for (Int J = 1; j <= N; j ++) if (Dist [I] [k] + dist [k] [J] <Dist [I] [J]) {Dist [I] [J] = DIST [I] [k] + dist [k] [J]; path [I] [J] = K; // path records the maximum vertex in the path} void output (int I, Int J) // recursively outputs the path. I is the starting point, J is the end {if (I = J) return; If (path [I] [J] = 0) cout <j <''; else {output (I, path [I] [J]); output (path [I] [J], j );}}