Dijkstra algorithm to find the shortest path is simpler

Source: Internet
Author: User

I think it's a lot easier than the code in the book anyway.

Some of the main core code or refer to the previous blog, I think that the Dij writing is good, it is worth to savor

Comment on the words of the blog, Vim does not know how to comment


#include <iostream>using namespace std; const int MAXINT = 999; Const int maxnum = +; int dist[maxnum]; int Pre[max NUM]; int c[maxnum][maxnum]; void Dij (int number, int sn, int *dist, int *pre, int c[maxnum][maxnum]) {bool S[maxnum]; fo R (int i = 1; i<= number; i++) {dist[i] = c[sn][i];s[i] = 0; if (dist [i] = = Maxint) {Pre[i] = 0;} else {pre[i] = sn;}} dist [SN] = 0; S[SN] = 1; for (int i = 2; i<= number; i++) {int pas = maxint; int u = sn;for (int j = 1; j<= number; j + +) if ((!s[j]) && Dist[j] <pas) {u = j;p as = Dist[j];} S[u] = 1; for (int j = 1;j<=number; j + +) {if ((!s[j]) && C[u][j] <maxint) {int newdist = dist[u] +c[u][j]; if (Newdist < dist[j]) {Dist[j] = newdist;p Re[j] = u;}}}} void SearchPath (int sour_num, int want_num) {cout << "the best-to-want_num ' s distance is"; cout << dist[ Want_num];} int main () {cout << "input the number of Graph:" <<endl;int number; cin >> number; cout << "Input the LiNe-number of Graph "&LT;&LT;ENDL; int line_n; cin >> line_n; int A, b, Len; for (int i = 1; I <= number; i++) {f or (int j = 1; J <= Number, J + +) {C[i][j] = maxint;}} for (int i = 1; I <= line_n; i++) {cin >> a >> b >> len; if (Len < c[a][b]) {c[a][b] = len; c[b][a ] = len;}} for (int i = 1;i <= number; i++) {dist[i] = maxint;} for (int i = 1; I <= number, i++) {for (int j = 1; j<= number; J + +) {cout << c[i][j]<< ";} cout << Endl;} cout << "Use the Dij ..." <<endl;D ij (number, 1, Dist, Pre, c); cout << "Input the Want_num:" &LT;&L T;endl; int want_num; cin >> Want_num; SearchPath (1, want_num);}



Dijkstra algorithm to find the shortest path is simpler

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.