#include <iostream> #include <vector> #include <stack> #define MaxSize 10 #define eletype int using namespace std; bool visited[MaxSize]; typedef struct AdjListGraph { int adjlist[MaxSize][MaxSize]; //邻接矩阵 eletype data[MaxSize]; int vex; //顶点数 int edge; //边数 }; void Init(AdjListGraph &G) { //初始化为未访问 for (int i = 0; i < MaxSize; i++) { visited[i] = false; for (int j = 0; j < MaxSize; j++) { G.adjlist[i][j] = 999; //表示无穷大 } } } int Location(AdjListGraph &G, eletype c) { //寻找顶点数据的邻接点 for (int i = 0; i < G.vex; i++) { if (G.data[i] == c) { return i; } } return -1; } void Create(AdjListGraph &G) { //创建图 cout << "请输入该图的顶点数以及边数:" << endl; cin >> G.vex >> G.edge; cout << "请输入相关顶点:" << endl; for (int i = 0; i < G.vex; i++) { cin >> G.data[i]; } eletype a, b; int c; int m, n; cout << "请输入相关边的顶点以及权值:" << endl; for (int i = 0; i < G.edge; i++) { cin >> a >> b>>c; m = Location(G, a); //寻找顶点号 n = Location(G, b); if (m != -1 && n != -1) { //寻找到位置 G.adjlist[m][n] = c; } } } void Dijkstra(AdjListGraph &G,vector<int> &p, vector<int> &dist,int v) { vector<int> vec; vec.push_back(v); visited[v] = true; //设置已访问过 //初始化dist dist.assign(G.vex, 999); p.assign(G.vex, -1); dist[v] = 0; //到自己的最短路径距离为0 for (int i = 0; i < G.vex; i++) { if (G.adjlist[v][i] != 999) { dist[i] = G.adjlist[v][i]; } } int count = G.vex; while (count > 1) { //选取Vj int min = 999, tag; for (int i = 0; i < vec.size(); i++) { for (int j = 0; j < G.vex; j++) { if (visited[j] == false && min > G.adjlist[vec[i]][j]) { min = G.adjlist[vec[i]][j]; //转换 tag = j; } } } vec.push_back(tag); //寻找到中继点 visited[tag] = true; //设置已访问过 //更新距离 for (int i = 0; i < G.vex; i++) { if (visited[i] == false && dist[tag] + G.adjlist[tag][i] < dist[i]) { dist[i] = dist[tag] + G.adjlist[tag][i]; p[i] = tag; } } count--; } } void Path(AdjListGraph &G,vector<int> &p,int begin,int end) { //输出路径 stack<eletype> s; s.push(G.data[end]); while (p[end] != -1) { s.push(G.data[p[end]]); end = p[end]; } s.push(G.data[begin]); //先进先出 while (!s.empty()) { cout << s.top() << " "; s.pop(); } } int main() { AdjListGraph G; vector<int> p; vector<int> dist; Init(G); Create(G); //创建图 Dijkstra(G,p,dist,0); Path(G,p,0,2); system("pause"); return 0; } /* 5 10 1 2 3 4 5 1 2 10 1 5 5 2 5 2 5 2 3 2 3 1 5 3 9 5 4 2 4 1 7 3 4 4 4 3 6 */
图的Dijkstra算法
猜你喜欢
转载自blog.csdn.net/coolsunxu/article/details/80671494
今日推荐
周排行