最短路径(迪克斯特拉算法)

问题:每个城市间的距离不一样,任意选择两个城市,求出两个城市间的最短距离

分析:用图来表示城市和城市间的距离(邻接矩阵),转变成求图的最短路径

 

shortestPath.h

#include <stdio.h> #define NUMVERTICES 10 #define MAXNUM 2147483647 class Graph { private: int Edge[NUMVERTICES][NUMVERTICES]; //图的邻接矩阵 int dist[NUMVERTICES]; //从顶点0到其他个点的最短路径长度 int path[NUMVERTICES]; //存放最短路径上顶点的前一顶点号码,用来存储最短路径 int S[NUMVERTICES]; //存放已经处理的顶点号 public: Graph(int *gra, int size); void shortestPath(int startPos, int size); void printShortestPath(int endPos); };

 

shortestPath.cpp

#include "shortestPath.h" Graph::Graph(int *gra, int size) { for (int i = 0; i < NUMVERTICES; i++) { for (int j = 0; j < NUMVERTICES; j++) { Edge[i][j] = MAXNUM; } } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { Edge[i][j] = *((gra+i*size)+j); } } } void Graph::shortestPath(int startPos, int size) { int i; int j; int k; for (i = 0; i < size; i++) { dist[i] = Edge[startPos][i]; if (i != startPos && dist[i] <= MAXNUM) { path[i] = startPos; } else { path[i] = -1; } S[i] = 0; } S[startPos] = 1; dist[startPos] = 0; for (i = 0; i < size - 1; i++) { int min = MAXNUM; int curPos = startPos; for (j = 0; j < size; j++) { if (!S[j] && dist[j] < min) { curPos = j; min = dist[j]; } } S[curPos] = 1; for (k = 0; k < size; k++) { if (!S[k] && Edge[curPos][k] < MAXNUM && dist[curPos] + Edge[curPos][k] < dist[k]) { dist[k] = dist[curPos] + Edge[curPos][k]; path[k] = curPos; } } } } void Graph::printShortestPath(int endPos) { if (0 >= endPos) { printf("The shortest path is: /n"); } else { printShortestPath(path[endPos]); } printf(" --> %d", endPos); }

 

main.cpp

#include "shortestPath.h" int main() { //int A[5][5] = {{0, 10, MAXNUM, 30, 100}, {MAXNUM, 0, 50, MAXNUM, MAXNUM}, //{MAXNUM, MAXNUM, 0, MAXNUM, 10}, {MAXNUM,MAXNUM, 20, 0, 60}, {MAXNUM, MAXNUM, MAXNUM, MAXNUM, 0}}; //int A[8][8] = {{0, 10, MAXNUM, MAXNUM, 60, MAXNUM, MAXNUM, 1000}, {MAXNUM, 0, 50, MAXNUM, MAXNUM, 150, MAXNUM, MAXNUM}, //{MAXNUM, MAXNUM, 0, 100, MAXNUM, MAXNUM, MAXNUM, MAXNUM}, {MAXNUM, MAXNUM, MAXNUM, 0, 5, MAXNUM, MAXNUM, MAXNUM}, {MAXNUM, MAXNUM, MAXNUM, MAXNUM, 0, 60, 10, MAXNUM}, //{MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, 0, 100, 800}, {MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, 0, 20}, {MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, 0}}; int A[8][8] = {{0, 10, MAXNUM, MAXNUM, 10, MAXNUM, MAXNUM, 580}, {MAXNUM, 0, 50, MAXNUM, MAXNUM, 150, MAXNUM, MAXNUM}, {MAXNUM, MAXNUM, 0, 100, MAXNUM, MAXNUM, MAXNUM, MAXNUM}, {MAXNUM, MAXNUM, 100, 0, 5, MAXNUM, MAXNUM, MAXNUM}, {MAXNUM, MAXNUM, MAXNUM, 5, 0, 60, 10, MAXNUM}, {MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, 0, 100, 100}, {MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, 0, 220}, {MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, MAXNUM, 0}}; Graph gr = Graph(&A[0][0], 8); gr.shortestPath(0, 8); gr.printShortestPath(7); return 0; }

 

你可能感兴趣的:(算法,存储,Class,Graph,Path)