Dijjkstra
- #include <iostream>
- #include <memory.h>
- #include <stdio.h>
- using namespace std;
- #define INF 65535
- const int MAXV = 7;
- typedef struct{
- int n;
- int edges[MAXV][MAXV];
- }Graph;
- // 1
- void Dijkstra(Graph graph, int v);
- // 2
- void Ppath(int path[], int i, int v);
- void Dispath(int dist[], int path[], int s[], int n, int v);
- int main(int argc, char *argv[])
- {
- Graph graph;
- int edges[][MAXV] = {
- {0, 4, 6, 6, INF, INF, INF},
- {INF, 0, 1, INF, 7, INF, INF},
- {INF, INF, 0, INF, 6, 4, INF},
- {INF, INF, 2, 0, INF, 5, INF},
- {INF, INF, INF, INF, 0, INF, 6},
- {INF, INF, INF, INF, 1, 0, 8},
- {INF, INF, INF, INF, INF, INF, 0}
- };
- memcpy(graph.edges, edges, MAXV*MAXV*sizeof(int));
- graph.n = MAXV;
- Dijkstra(graph, 0);
- return 0;
- }
- // 1
- void Dijkstra(Graph graph, int v)
- {
- // put the miniDist
- int dist[MAXV], path[MAXV];
- // put the uses node
- int s[MAXV];
- int mindist, i, j, u;
- // Init
- for(i=0; i<graph.n; i++){
- dist[i] = graph.edges[v][i];
- s[i] = 0;
- if(graph.edges[v][i]<INF)
- path[i] = v;
- else
- path[i] = -1;
- }
- s[v] = 1;
- path[v] = 0;
- for(i=0; i<graph.n; i++){
- mindist = INF;
- // 寻找与V点距离最小的点
- for(j=0; j<graph.n; j++){
- if(s[j]==0 && dist[j]<mindist){
- u = j; // point
- mindist = dist[j];
- }
- }// end for-j
- // 更新距离
- s[u] = 1;
- if(u==5){
- int temp=3;
- }
- for(j=0; j<graph.n; j++){
- if(s[j]==0){
- if(graph.edges[u][j]<INF&&dist[u]+graph.edges[u][j]<dist[j]){
- dist[j] = dist[u] + graph.edges[u][j];
- path[j] = u;
- }
- }
- }// end for-j
- }// end for-i
- Dispath(dist, path, s, graph.n, v);
- }
- // 2-1
- void Ppath(int path[], int i, int v)
- {
- int k;
- k = path[i];
- if(k ==v)
- return;
- Ppath(path, k, v);
- cout<<k<<",";
- }
- void Dispath(int dist[], int path[], int s[], int n, int v)
- {
- int i;
- for(i=0; i<n; i++){
- if(s[i] ==1){
- printf("从%d到%d的最短路径长度为:%d\t 路径为:", v, i, dist[i]);
- cout<<v<<",";
- Ppath(path, i, v);
- cout<<i<<endl;
- }else{
- printf("从%d到%d不存在路径\n", v, i);
- }
- }
- }