Summary of the shortest path algorithm

One, Floyd

int n;
void floyd(){
    
    
	for(int k=1;k<=n;k++){
    
    
		for(int i=1;i<=n;i++){
    
    
			for(int j=1;j<=n;j++){
    
    
				if(maps[i][j]>maps[i][k]+maps[k][j]){
    
    
					maps[i][j]=maps[i][k]+maps[k][j];
				}
			}
		}
	}
}

Two, Dijkstra

#define INF 0x3f3f3f3f
int n,m;
int dis[M];
int vis[M];
int maps[M][M];
void init(){
    
    
	for(int i=1;i<=n;i++){
    
    
		for(int j=1;j<=n;j++){
    
    
			maps[i][j]=INF;
		}
		maps[i][i]=0;
	}
	memset(vis,0,sizeof(vis));
}
void dijkstra(int s){
    
    
	for(int i=1;i<=n;i++) dis[i]=INF;
	dis[s]=0;
	for(int i=1;i<=n;i++) dis[i]=maps[s][i];
	for(int i=1;i<=n;i++){
    
    
		int Min=INF,k;
		for(int j=1;j<=n;j++){
    
    
			if(!vis[j]&&Min>dis[j]) Min=dis[j],k=j;
		}
		vis[k]=1;
		for(int j=1;j<=n;j++){
    
    
			if(!vis[j]&&dis[j]>maps[k][j]+dis[k]) dis[j]=maps[k][j]+dis[k];
		}
	}
}
//dijkstra(1) 指的是选定1为源点
//cout<<dis[n] 指的是输出 1 到 n 的最短距离	

Three, Bellman_ford

#define M 105
#define INF 0x3f3f3f3f
struct node{
    
    
    int u,v,w;
}edge[M];
int dis[M];
int n,m,s;
void init(){
    
    
    cin>>n>>m>>s;
    for(int i=1;i<=n;i++){
    
    
        dis[i]=INF;
    }
    dis[s]=0;
    for(int i=1;i<=m;i++){
    
    
        cin>>edge[i].u>>edge[i].v>>edge[i].w;
        if(edge[i].u==s){
    
    
            dis[edge[i].v]=edge[i].w;
        }
    }
}
bool bellmanford(){
    
    
    for(int i=1;i<=n;i++){
    
    
        for(int j=1;j<=m;j++){
    
    
            if(dis[edge[j].v]>dis[edge[j].u]+edge[j].w){
    
    
                dis[edge[j].v]=dis[edge[j].u]+edge[j].w;
            }
        }
    }
    int flag=1;
    for(int i=1;i<=m;i++){
    
    
        if(dis[edge[i].v]>dis[edge[i].u]+edge[i].w){
    
    
            flag=0;
            break;
        }
    }
    return flag;
}
//nodenum 节点数
//edgenum 边数
//source  源点
//distance 距离

I wanted to write down my thoughts in detail, so let's just talk about it briefly.
The difference between Dijkstra and Bellman is that one uses the point to find the shortest path, and the other uses the edge to find the shortest path, single source point. After selection, first find the edge weights of the points directly connected to this point, and then compare them. Why is it a double loop, because it relaxes once, and it is accurate all over again. There is also spfa, which will be added later.
What I write is all boards. I have just started learning these two days. If I make a mistake, I will change it.

Guess you like

Origin blog.csdn.net/iuk11/article/details/108403425