In the previous blog, I talked about the Dijkstra algorithm. In this blog, I want to explain the Floyd algorithm. The Dijkstra algorithm is a greedy algorithm, and the Floyd algorithm is an algorithm for dynamic planning:
The specific algorithm is as follows:
One matrix is used to store the shortest path, and the other matrix is used to store the front vertex;
#include <iostream>using namespace std;#define Max 5#define Infinity 65535void main(){int V[Max][Max]={0,8,32,Infinity,Infinity,12,0,16,15,Infinity,Infinity,29,0,Infinity,13,Infinity,21,Infinity,0,7,Infinity,Infinity,27,19,0};int G[Max][Max];for(int i=0;i<Max;i++){for(int j=0;j<Max;j++){G[i][j]=-1;}}for(int k=0;k<Max;k++){for(int i=0;i<Max;i++){for(int j=0;j<Max;j++){if(V[i][k]+V[k][i]<V[i][j]){V[i][j]=V[i][k]+V[k][j];G[i][j]=k;}}}}for(int i=0;i<Max;i++){for(int j=0;j<Max;j++){cout<<V[i][j]<<" ";}cout<<endl;}for(int i=0;i<Max;i++){for(int j=0;j<Max;j++){cout<<G[i][j]<<" ";}cout<<endl;}}
Shortest Path-Floyd algorithm