求图中任意两个顶点间的最短路径

#include 
using namespace std;
const int MAXVERTEXNUM = 100;
const int MAX_WEIGHT = 32767;
struct MGraph
{
    char vers[MAXVERTEXNUM];
    int  edges[MAXVERTEXNUM][MAXVERTEXNUM];
    int  n, e;
};


void CreateMGraph(MGraph *G, int adjmatrix[][MAXVERTEXNUM])
{
    cout << "请输入图的顶点和边数:" << endl;
    cin >> G->n >> G->e;
    cout << "请输入顶点信息:" << endl;
    for(int i = 0; i < G->n; i++)
        cin >> G->vers[i];
    for(i = 0; i < G->n; i++)
        for(int j = 0; j < G->n; j++)
            adjmatrix[i][j] = MAX_WEIGHT;
    for(int k = 0; k < G->e; k++)
    {
        int x, y, dut;
        cout << "请输入第" << k + 1 << "条边所依附的顶点及其权值:" << endl;
        cin >> x >> y >> dut;
        adjmatrix[x][y] = dut;
    }
}

void shortestpath(MGraph *G, int adjmatrix[][MAXVERTEXNUM])
{
    int n = G->n;
    int dist[MAXVERTEXNUM][MAXVERTEXNUM];
    int path[MAXVERTEXNUM][MAXVERTEXNUM];
    int i, j;
    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++)
        {
            dist[i][j] = adjmatrix[i][j];
            if(i != j && dist[i][j] < MAX_WEIGHT)
                path[i][j] = i;
            else
                path[i][j] = -1;
        }
    for(int k = 0; k < n; k++)
        for(i = 0; i < n; i++)
            for(j = 0; j < n; j++)
                if(dist[i][j] > (dist[i][k] + dist[k][j]))
                {
                    dist[i][j] = dist[i][k] + dist[k][j];
                    path[i][j] = path[k][j];
                }
    cout << "每对顶点间的最短路径如下:" << endl;
    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++)
            if(i != j && dist[i][j] < MAX_WEIGHT)
            {
                int pathnum[MAXVERTEXNUM];
                int k = 0;
                int v = path[i][j];
                while(v != i && v != j)
                {
                    pathnum[k++] = v;
                    v = path[i][v];
                }
                cout << G->vers[i] << " ";
                while(k > 0)
                    cout << "->" << G->vers[pathnum[--k]] << " ";
                cout << "->" << G->vers[j] << "   长度为:" << dist[i][j] << endl;
            }
}

void main()
{
    int adjmatrix[MAXVERTEXNUM][MAXVERTEXNUM];
    MGraph G;
    CreateMGraph(&G, adjmatrix);
    shortestpath(&G, adjmatrix);
}

你可能感兴趣的:(数据结构与算法)