目的:求单源最短路径
辅助数组:
1、dist[]:用来记录源点到结点i的最短距离
2、s[]:用来记录结点i是否已经被收录
3、path[]:结点i是从path[i]过来的
算法步骤:
1、初始化:
如果两点之间没有直接路径,graph[i][j] 设置为最大值,否则记录每条边的权值
dist[]:如果有到源点的直接路径,则初始化为路径长度,否则初始化为最大值,表示没直接可达的路径。
s[]:除源点外,每个元素初始化为0,1代表收录,0代表未收录
path[]:初始化为-1;
2、从未收录的顶点中,找寻dist最小的元素作为这次收录的顶点,更新源点到每个结点的最小距离,以及对应的path
3、重复上述过程,直到所有的点都被收录
代码实现
#include "stdafx.h";
#include <iostream>
#include<stack>
using namespace std;
#define MaxValue 10000
typedef int VertexType;
#define MaxVertexNum 100
#define Init -1
int Graph[MaxVertexNum][MaxVertexNum];
int path[MaxVertexNum];
int dist[MaxVertexNum];
int s[MaxVertexNum];
int nv;
int ne;
void build(){
cout << "请输入顶点个数"<<endl;
cin >> nv;
//初始化图
for(int i = 1;i <= nv;i++) {
for(int j = 1; j <= nv;j++){
if(i == j) Graph[i][j] = 0;
else
Graph[i][j] = MaxValue;
}
}
//初始化路径,距离以及收录情况
for(int i = 1;i <= nv;i++){
path[i] = Init;
s[i] = 0;//0代表未收录,1代表收录
}
for(int i = 0;i <= nv; i++){
dist[i] = MaxValue;
}
//初始化边
cout << "请输入边数"<<endl;
cin >> ne;
cout << "请输入边信息,v1 v2 weight" << endl;
int v1,v2,weight;
for(int i = 1;i <= ne;i++){
cin >> v1 >> v2 >> weight;
if(v1>=1 && v1 <= nv && v2 >= 1 && v2<= nv) {
Graph[v1][v2] = weight;
}
}
}
void create(VertexType v) {
build();
dist[v] = 0;
s[v] = 1;
for(int i = 1;i<=nv;i++){
if(i == v){
continue;
}else{
if(Graph[v][i] != MaxValue){
path[i] = v;
dist[i] = Graph[v][i];
}
}
}
}
//查找到原点距离最小的点
VertexType findMin(VertexType v) {
int min = 0;
for(int i =1;i <= nv;i++){
if(i != v && s[i] == 0 && dist[i] < dist[min]){
min = i;
}
}
return min;
}
void Dijkstra(VertexType v){
create(v);
while(1){
VertexType cur = findMin(v);
if(cur == 0){
break;
}
s[cur] = 1;//收录
for(int i = 1;i <= nv;i++){
if(s[i]==0 && dist[cur]+Graph[cur][i] < dist[i]){
dist[i] = dist[cur] + Graph[cur][i];
path[i] = cur;
}
}
}
}
void OutPut(VertexType v) {
for(int i = 1;i <= nv;i++){
cout << dist[i] << " ";
}
cout << endl;
for(int i = 1;i <= nv; i++) {
cout << path[i] << " ";
}
cout << endl;
for(int i = 1;i <= nv;i++){
if(i == v) continue;
else{
cout << v << "到"<<i<<"的最短路径:";
stack<VertexType> p;
int r = i;
while(r != v){
p.push(r);
r = path[r];
}
while(!p.empty()){
cout << p.top() << " ";
p.pop();
}
}
cout << endl;
}
}
int main() {
VertexType source = 2;
Dijkstra(source);
OutPut(source);
cin >> source;
}