这一篇写一下Dijkstra算法。当初学习数据结构的课件找不到了,就在网上找了两张图片,有一个有权无向图以及迪杰斯特拉算法的原理思想。
以下是C++实现代码:
#include<iostream>
#include<limits.h>
#define MAXVEX 100
using namespace std;
typedef struct
{
int matrix[MAXVEX][MAXVEX];
int numNodes, numEdges;
} Graph;
void CreateGraph(Graph *Gp)
{
int i, j, k, w;
bool isDirected;
cout<<"无向图请输入0,有向图请输入1"<<endl;
cin>>isDirected;
cout<<"请输入顶点数和边数(空格分隔):"<<endl;
cin>>Gp->numNodes>>Gp->numEdges;;
for (i=1;i<=Gp->numNodes;i++)
{
for (j=1;j<=Gp->numNodes;j++)
{
if (i==j)
Gp->matrix[i][j]=0;
else
Gp->matrix[i][j]=INT_MAX;
}
}
cout<<"请输入边(vi, vj)和权值w,三个变量空格分隔即可:"<<endl;
for (k=0;k<Gp->numEdges;k++)
{
cin>>i>>j>>w;
Gp->matrix[i][j]=w;
if(!isDirected)
Gp->matrix[j][i]=Gp->matrix[i][j];
}
}
void ShowGraph(Graph M){
int i, j;
for(i=1;i<=M.numNodes;i++){
for(j=1;j<=M.numNodes;j++){
if(M.matrix[i][j]!=INT_MAX)
cout<<M.matrix[i][j]<<" ";
else
cout<<"*"<<" ";
}
cout<<endl;
}
}
void Dijkstra(Graph M, int start){
int count_S=0;
bool *isFind=new bool[M.numNodes+1]; //记录是否加入到S集
int *Distance=new int[M.numNodes+1]; //记录节点i到start节点的距离
for(int i=1;i<=M.numNodes;i++){
isFind[i]=false;
Distance[i]=M.matrix[start][i];
}
isFind[start]=true;
count_S++;
int last_Find;
while(count_S<M.numNodes){
int max_Distance=INT_MAX;
for(int i=1;i<=M.numNodes;i++){ //获取距离start节点最近的点
if(!isFind[i]&&Distance[i]<max_Distance){
last_Find=i;
max_Distance=Distance[i];
}
}
isFind[last_Find]=true;
count_S++;
for(int i=1;i<=M.numNodes;i++){
if(!isFind[i]&&M.matrix[last_Find][i]!=INT_MAX){
Distance[i]=Distance[last_Find]+M.matrix[last_Find][i] < Distance[i] ? Distance[last_Find]+M.matrix[last_Find][i] : Distance[i] ;
}
}
}
cout<<"从开始点"<<start<<"到各点的最短距离为:"<<endl;
for(int i=1;i<=M.numNodes;i++)
cout<<"到"<<i<<"的距离为:"<<Distance[i]<<endl;
delete[]isFind;
delete[]Distance;
}
int main(){
Graph M;
CreateGraph(&M);
cout<<"邻接矩阵为:"<<endl;
ShowGraph(M);
int start;
cout<<"请输入起始点"<<endl;
cin>>start;
Dijkstra(M, start);
return 0;
}
运行结果: