Shortest Path Dijkstra Algorithm

Source: Internet
Author: User
# Include <stdio. h> # include <string. h> # define num 100 # define maxint 10000 void Dijkstra (int n, int V, int Dist [], int Prev [], int C [] [num]) {int I, j; bool s [num]; for (I = 1; I <= N; I ++) {Dist [I] = C [v] [I]; s [I] = false; If (Dist [I]> maxint) Prev [I] = 0; else Prev [I] = V;} Dist [v] = 0; s [v] = true; for (I = 1; I <n; I ++) {int TMP = maxint; int u = V; For (j = 1; j <= N; j ++) if (! (S [J]) & (Dist [J] <TMP) {u = J; TMP = DIST [J];} s [u] = 1; for (j = 1; j <= N; j ++) if (! (S [J]) & C [u] [J] <maxint) {int newdist = DIST [u] + C [u] [J]; if (newdist <Dist [J]) {Dist [J] = newdist; Prev [J] = u ;}}} int main () {int M, N; while (scanf ("% d", & N, & M )! = EOF & (M | N) {int I, j; int Dist [num] = {0}; int Prev [num] = {0 }; int C [num] [num]; memset (C, 1, sizeof (c); // 16843009 // printf ("% d ", c [0] [0]); int V, W, edge; for (I = 0; I <m; I ++) {scanf ("% d", & V, & W, & edge); C [v] [W] = edge;} Dijkstra (n, 1, dist, Prev, c); for (I = 2; I <= N; I ++) printf ("% d", DIST [I]); printf ("\ n"); For (j = 2; j <= N; j ++) {printf ("% d", J ); int T = Prev [J]; while (T! = 1) {printf ("--> % d", T); t = Prev [T];} printf ("--> 1 \ n ");}} return 0 ;}

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.