dijkstra求单源最短路径以及路径记录

来源:互联网 发布:精美ppt制作软件 编辑:程序博客网 时间:2024/06/05 07:01
#define MAXINT 0xff#define MAXSIZE 1000#include#includeusing namespace std;int amapBorder[MAXSIZE][MAXSIZE];int vNum = 6;void initmap(){for(int i = 1 ; i < vNum + 1 ; i++){for(int j = 1 ; j < vNum + 1 ; j++){amapBorder[i][j] = MAXINT;}}amapBorder[1][2] = 6;amapBorder[1][3] = 3;amapBorder[2][3] = 2;amapBorder[2][4] = 5;amapBorder[3][4] = 3;amapBorder[3][5] = 4;amapBorder[4][5] = 2;amapBorder[4][6] = 3;amapBorder[5][6] = 5;for(int i = 1 ; i < vNum + 1 ; i++){for(int j = 1 ; j < vNum + 1 ; j++){if(i == j){amapBorder[i][j] = 0;}if(amapBorder[i][j] == MAXINT){amapBorder[i][j] = amapBorder[j][i];}}}}void dijstra(int vo){int U[7] = {0} , dist[7] = {0};int path[7];for(int i = 1 ; i < vNum + 1 ; i++){dist[i] = amapBorder[vo][i];if(dist[i] == MAXINT){path[i] = -1;}else{path[i] = vo; //记录当前节点的上一个节点}}for(int i = 1 ; i < vNum + 1 ; i ++){int minNum = MAXINT;int temp = vo;for( int j = 1 ; j < vNum + 1 ; j++){if((!U[j]) && dist[j] < minNum ){minNum = dist[j];temp = j;}}U[temp] = 1;for(int j = 1; j < vNum + 1 ; j++){if(!U[j] && amapBorder[temp][j] < MAXINT){if(dist[j] > amapBorder[temp][j] + dist[temp]){dist[j] = amapBorder[temp][j] + dist[temp];path[j] = temp;}}}}for(int i = 1; i < vNum + 1 ; i++){cout << i << ": " << dist[i] << " ";int j = i;cout << j << "<-";while(path[j] != vo){j = path[j];cout << j << "<-";}cout << vo << endl;}}