Dijkstra
#include<bits/stdc++.h>
using namespace std;
const int MaxVertexNum=100;
map<char,int> NodeIndex;
typedef struct{
char Vex[MaxVertexNum];
int Edge[MaxVertexNum][MaxVertexNum];
int vexnum,arcnum;
}MGraph;
void Dijkstral(MGraph G,char x){
vector<int> dist(G.vexnum,INT_MAX);
vector<int> flag(G.vexnum,0);
dist[NodeIndex[x]]=0;
for(int i=0;i<G.vexnum;i++){
int minDis=INT_MAX,k;
for(int j=0;j<G.vexnum;j++){
if(flag[j]==0 && minDis>dist[j]){
minDis=dist[j];
k=j;
}
}
flag[k]=1;
for(int j=0;j<G.vexnum;j++){
if(G.Edge[k][j]!=INT_MAX&&dist[j]>dist[k]+G.Edge[k][j])
dist[j]=dist[k]+G.Edge[k][j];
}
}
for(int i=0;i<G.vexnum;i++){
cout<<x<<"到"<<G.Vex[i]<<"的最小距离为"<<dist[i]<<endl;
}
}
int main(){
MGraph G;
cout<<"请输入结点总数与边数"<<endl;
cin>>G.vexnum>>G.arcnum;
char vnode;
cout<<"请输入结点名称"<<endl;
for(int i=0;i<G.vexnum;i++){
cin>>vnode;
G.Vex[i]=vnode;
NodeIndex[vnode]=i;
}
for(int i=0;i<G.vexnum;i++){
for(int j=i+1;j<G.vexnum;j++){
G.Edge[i][j]=INT_MAX;
G.Edge[j][i]=INT_MAX;
}
G.Edge[i][i]=0;
}
char vex1,vex2;
int weight;
cout<<"请输入相连的结点以及边权值"<<endl;
for(int i=0;i<G.arcnum;i++){
cin>>vex1>>vex2>>weight;
G.Edge[NodeIndex[vex1]][NodeIndex[vex2]]=weight;
}
char x;
cin>>x;
Dijkstral(G,x);
return 0;
}
Floyd
#include<bits/stdc++.h>
using namespace std;
const int MaxVertexNum=100;
map<char,int> NodeIndex;
int dist[MaxVertexNum][MaxVertexNum];
typedef struct{
char Vex[MaxVertexNum];
int Edge[MaxVertexNum][MaxVertexNum];
int vexnum,arcnum;
}MGraph;
int Floyd(MGraph G){
for(int k=0;k<G.vexnum;k++)
for(int i=0;i<G.vexnum;i++)
for(int j=0;j<G.vexnum;j++)
if(dist[i][j]>dist[i][k]+dist[k][j])
dist[i][j]=dist[i][k]+dist[k][j];
cout<<"任意顶点对的最短路径长度"<<endl;
for(int i=0;i<G.vexnum;i++){
for(int j=0;j<G.vexnum;j++){
cout<<setw(4)<<dist[i][j]<<" ";
}
cout<<endl;
}
}
int main(){
MGraph G;
cout<<"请输入结点总数与边数"<<endl;
cin>>G.vexnum>>G.arcnum;
char vnode;
cout<<"请输入结点名称"<<endl;
for(int i=0;i<G.vexnum;i++){
cin>>vnode;
G.Vex[i]=vnode;
NodeIndex[vnode]=i;
}
for(int i=0;i<G.vexnum;i++){
for(int j=i+1;j<G.vexnum;j++){
G.Edge[i][j]=INT_MAX;
G.Edge[j][i]=INT_MAX;
dist[i][j]=INT_MAX;
dist[j][i]=INT_MAX;
}
G.Edge[i][i]=0;
dist[i][i]=0;
}
char vex1,vex2;
int weight;
cout<<"请输入相连的结点以及边权值"<<endl;
for(int i=0;i<G.arcnum;i++){
cin>>vex1>>vex2>>weight;
G.Edge[NodeIndex[vex1]][NodeIndex[vex2]]=weight;
dist[NodeIndex[vex1]][NodeIndex[vex2]]=weight;
}
Floyd(G);
return 0;
}