最短路径 Dijkstra算法

来源:互联网 发布:vue.js chrome插件 编辑:程序博客网 时间:2024/06/03 13:46
typedef struct MGraph{    int vexnum,arcnum;    int AdjMatrix[vertex_num][vertex_num];    int vertex[vertex_num];}MGraph;//图的存储结构使用邻接矩阵表示vector<vector<int>> ShortestPath_DIJ(MGraph G){int flag[vertex_num];//记录当前节点是不是已经加入最短路径vector<vector<int>>p;int D[vertex_num];//记录当前最短路径集合到其余各点的最短路径for (int v=0;v<G.vexnum;v++){//初始化flag[v]=false;D[v]=G.AdjMatrix[0][v];vector<int> temp_vec;p.push_back(temp_vec);if (D[v]<MaxInt){p[v].push_back(0);p[v].push_back(v);}}D[0]=0;flag[0]=true;int select_v;for (int i=0;i<G.vexnum;i++){int min_len=MaxInt;for (int w=0;w<G.vexnum;w++){if (!flag[w]){if (D[w]<min_len){//当前D中最小的路径长度,作为下一个候选节点加入到最短路径中select_v=w;min_len=D[w];}}}flag[select_v]=true;for (int w=0;w<G.vexnum;w++){if (!flag[w]&&(min_len+G.AdjMatrix[select_v][w]<D[w])){D[w]=min_len+G.AdjMatrix[select_v][w];p[w]=p[select_v];p[w].push_back(w);}}}return p;}

0 0
原创粉丝点击