#include "iostream" #include "memory.h" using namespace std;const int num = 9; Number of nodes # define Infinity 65535void Dijk (int *distance, int *p, int graphic[num][num], int source) {//distance record from source to other node The shortest distance bool Isvisted[num]; Records whether a node has been visited by memset (p, 0, sizeof (p)); Recorded in the shortest path, the parent node of the current node memset (isvisted, False, sizeof (isvisted));//initialize for (int i = 0; i < num; i++) {Distance[i] = Graphic[s Ource][i];} Isvisted[source] = True;distance[source] = 0;for (int i = 0; i < num; i++) {int min = Infinity;int index;//Find the shortest source distance The non-visited node for (int j = 0; j < Num; J + +) {if (!isvisted[j] && distance[j] < min) {index = J;min = Distance[j];} }isvisted[index] = true;//fix the shortest distance from other nodes to source for (int j = 0; j < Num; J + +) {if (!isvisted[j] && (min + graphic[in DEX][J]) < Distance[j]) {Distance[j] = min + graphic[index][j];p [j] = Index;}}} int main () {int graphic[num][num];for (int i = 0; i < num; i++) for (int j = 0; j < Num; J + +) {if (i = = j) Graphic[i][j] = 0;elsegraphic[i][j] = Infinity;}GRAPHIC[0][1] = 1;graphic[0][2] = 5;graphic[1][0] = 1;graphic[1][2] = 3;graphic[1][3] = 7;graphic[1][4] = 5;graphic[2][0] = 5;graphic[2][1] = 3;graphic[2][4] = 1;graphic[2][5] = 7;graphic[3][1] = 7;graphic[3][4] = 2;graphic[3][6] = 3;graphic[4] [1] = 5;graphic[4][2] = 1;graphic[4][3] = 2;graphic[4][5] = 3;graphic[4][6] = 6;graphic[4][7] = 9;graphic[5][2] = 7;graphi C[5][4] = 3;graphic[5][7] = 5;graphic[6][3] = 3;graphic[6][4] = 6;graphic[6][7] = 2;graphic[6][8] = 7;graphic[7][4] = 9;gr APHIC[7][5] = 5;graphic[7][6] = 2;graphic[7][8] = 4;graphic[8][6] = 7;graphic[8][7] = 4;int distance[num];int P[num];d Ijk ( Distance, p, graphic, 1); for (int i = 0; i < num; i++) {cout << distance[i] << Endl;} return 0;}
Dijkstra algorithm to find the shortest path