C++實現Dijkstra演算法

來源:互聯網
上載者:User

標籤:

#define _CRT_SECURE_NO_WARNINGS#include<iostream>#include<string>#include<iomanip>#include<cstdlib>#include<cstdio>#include<vector>#include<algorithm>#include<cmath>#include<map>#include<cassert>using namespace std;const int INF = INT_MAX;struct Node{int pre;int dist;bool visited;Node() : pre(-1), dist(INF), visited(false) {}};void dispT(vector<Node> & T) {for (int i = 0; i < T.size(); ++i) {cout << "Num: " << i << "  Dist: " << T[i].dist << "  Pre: " << T[i].pre << endl;}return;}int Extract_Min(vector<Node> & T) {int mark = -1;for (int i = 0; i < T.size(); ++i) {if (!T[i].visited) {if (mark == -1)mark = i;else if (T[i].dist < T[mark].dist)mark = i;}}return mark;}void Dijkstra(vector<vector<int> > & G, size_t src){//check validity.if (src >= G.size()) return;vector<Node> T(G.size());T[src].dist = 0;for (int i = 0; i < G.size(); ++i) {int tag = Extract_Min(T);assert(tag != -1);//debug.T[tag].visited = true;//update the weights of edges,taversing in the same manner as BFS.for (int j = 0; j < G.size(); ++j) {if (!T[j].visited && G[tag][j] != INF && T[j].dist > G[tag][j] + T[tag].dist) {T[j].dist = G[tag][j] + T[tag].dist;T[j].pre = tag;}}}//output.dispT(T);}int main(void){cout << "Dijkstra Algorithm for Directed Graph:" << endl;while (true) {int N;cout << "Number of Nodes: ";cin >> N;vector<vector<int> >G(N, vector<int>(N, INF));for (int i = 0; i < N; ++i)G[i][i] = 0;int M;cout << "Number of Edges: ";cin >> M;for (int i = 0; i < M; ++i) {int s, e;cin >> s >> e;cin >> G[s][e];}for (int src = 0; src < N; ++src) {cout << "From " << src << " :" << endl;Dijkstra(G, src);system("pause");}}system("pause");return 0;}

C++實現Dijkstra演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.