# 最短路径的迪克斯拉算法

0

#include<iostream>
#define NUMVERTICES 6
#define MAXNUM 214748364
using namespace std;
//迪克斯拉算法
class Graph
{
private:
int Edge[NUMVERTICES][NUMVERTICES];
int dist[NUMVERTICES];

int path[NUMVERTICES];
int S[NUMVERTICES];
public:
Graph(int *gra, int size);
void shortestPath(int startPos, int size);
void printShortestPath(int endPos);
};

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) //?????
{
cout<<"The shortest path is: ""\n"<<endl;
}
else
{
printShortestPath(path[endPos]); //??????
}
cout<<"-->"<<endPos;
cout<<endl;
}
int main()
{
int A[6][6]={{0,4,2,MAXNUM,MAXNUM,MAXNUM},
{MAXNUM,0,5,10,MAXNUM,MAXNUM},
{MAXNUM,MAXNUM,0,MAXNUM,3,MAXNUM},
{MAXNUM,MAXNUM,MAXNUM,0,MAXNUM,11},
{MAXNUM,MAXNUM,MAXNUM,4,0,MAXNUM},
{MAXNUM,MAXNUM,MAXNUM,MAXNUM,MAXNUM,0}};
Graph gr = Graph(&A[0][0], 6);
gr.shortestPath(0, 6);
gr.printShortestPath(5);
//return 0;
}

您需要登录以后才能回答，未注册用户请先注册