理论部分我就用:http://blog.sina.com.cn/s/blog_4b9aefc20100zu8h.html
希望到原文章看更详细的解释!
1 最短路径算法
在日常生活中,我们如果需要常常往返A地区和B地区之间,我们最希望知道的可能是从A地区到B地区间的众多路径中,那一条路径的路途最短。最短路径问题是图论研究中的一个经典算法问题, 旨在寻找图(由结点和路径组成的)中两结点之间的最短路径。 算法具体的形式包括:如下图,设A为源点,求A到其他各顶点(B、C、D、E、F)的最短路径。线上所标注为相邻线段之间的距离,即权值。(注:此图为随意所画,其相邻顶点间的距离与图中的目视长度不能一一对等)
图一:Dijkstra无向图
我们要做的就是模拟这个搜索过程,这种贪心算法的代价还是比较大的
原图来自:http://blog.sina.com.cn/s/blog_4b9aefc20100zu8h.html
这里利用path来记录路径,表示到达第i个点的最短路径上一个点是path[i]
//============================================================================ // Name : GraphPath.cpp // Author : YLF // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; #define MAX_DIST 1000 #define MAX 10 bool Dijk(int matrix[MAX][MAX], int *path, int src, int dst, int n); void ShowResult(int *path, int *dist, bool *visited, int n,int src, int dst); int main() { int matrix[MAX][MAX]; int n = 0; int src = 0; int dst = 0; int path[MAX]; int i = 0, j = 0; for(i=0;i<MAX;i++) for(j=0;j<MAX;j++) matrix[i][j] = MAX_DIST; cout<<"input number of node:"<<endl; cin>>n; cout<<"input dist between nodes:"<<endl; int row = 0, col = 0, length = 0; while(true){ cin>>row>>col>>length; if(row!=-1 && col!=-1 && length!=-1){ matrix[row][col] = length; matrix[col][row] = length; }else break; } for(i=0;i<n;i++){ for(j=0;j<n;j++) cout<<matrix[i][j]<<"\t"; cout<<endl; } cout<<"the src and dst:"; cin>>src>>dst; Dijk(matrix, path, src, dst, n); return 0; } bool Dijk(int matrix[MAX][MAX], int *path, int src, int dst, int n){ bool visited[n]; int dist[n]; int i = 0; for(i=0;i<n;i++){ visited[i] = false; if(src == i) dist[i] = 0; else dist[i] = MAX_DIST; } //先初始化visited 从src到可一步到达的点的距离 int mid = src; int minDist = MAX_DIST; bool flag = true; while(flag){ for(i=0;i<n;i++){ if(i != src){ int temp = dist[mid] + matrix[i][mid]; if(temp<dist[i]){ dist[i] = temp; path[i] = mid; } } } visited[mid] = true; minDist = MAX_DIST; for(i=0;i<n;i++){ if(!visited[i] && dist[i] < minDist){ minDist = dist[i]; mid = i; } } if(minDist >= MAX_DIST) flag = false; if(mid == dst) flag = false; } ShowResult(path, dist, visited, n, src, dst); return true; } void ShowResult(int *path, int *dist, bool *visited, int n,int src, int dst){ int i = 0; cout<<"path:"; int tempPath = dst; cout<<tempPath; while(tempPath != src){ cout<<"<--"<<path[tempPath]; tempPath = path[tempPath]; } cout<<endl<<"dist:"; for(i=0;i<n;i++){ cout<<dist[i]<<" "; } cout<<endl<<"visted:"; for(i=0;i<n;i++){ cout<<visited[i]<<" "; } }
测试结果如下:
input number of node: 6 input dist between nodes: 0 1 6 0 2 3 1 2 2 1 3 5 2 3 3 3 4 2 3 5 3 4 5 5 -1 -1 -1 1000 6 3 1000 1000 1000 6 1000 2 5 1000 1000 3 2 1000 3 1000 1000 1000 5 3 1000 2 3 1000 1000 1000 2 1000 5 1000 1000 1000 3 5 1000 the src and dst:0 5 path:5<--3<--2<--0 dist:0 5 3 6 8 9 visted:1 1 1 1 1 0