#include<stdio.h>
#include<string.h>
#include<vector>//涉及到和录入顺序相关的首先想到用vector接受
#include<algorithm>
#include<string>
#include<iostream>
#include<map>
using namespace std;
const int maxn=1000;
int INF=1e9;
/*
dijstra算法:每次从尚未加入到最短顶点的点中找最近的点,并利用它更新到其他节点上的点
*/
bool set[maxn];//已经找到最短路径的节点
int g[maxn][maxn];//邻接矩阵
int cost[maxn];//当前到点n的最短距离
int path[maxn];//到点n经过的前驱:最终是一个 双亲表示的树
int n;
void dijstra(int s){
//初始化所有和起点相关的
fill(cost,cost+n,INF);
fill(path,path+n,-1);
cost[s]=0;
for(int i=0;i<n;i++)
path[i]=i;//各自为根节点
for(int i=0;i<n;i++){
int min=INF,u=-1;//更新后仍为-1说明图不联通
for(int j=0;j<n;j++){
if(!set[j] && cost[j]<min){
min=cost[j];
u=j;
}
}
if(u==-1) return;//不连通
set[u]=true;
//利用u更新cost
for(int j=0;j<n;j++){
if(!set[j] && g[u][j]!=INF && cost[u]+g[u][j]<cost[j]){
cost[j]=cost[u]+g[u][j];
path[j]=u;
}
}
}
}
void DFS(int s,int e){//输出从s到e的路径
if(e==s){
printf("%d->",s);//递归到起点返回
}
else{
DFS(s,path[e]);
printf("%d->",e);//从起点返回时依次输出路径
}
}
int main(){
return 0;
}
Dijkstra算法
最新推荐文章于 2024-03-18 16:58:49 发布