路径搜索问题

来源:互联网 发布:node sass 安装 编辑:程序博客网 时间:2024/06/05 16:58

这个是学校的课设题目,单纯的套一下模板就可以出来的,我为了偷懒上了Floyd,有需要的同学请自取。

#include <stdio.h>#include <string>#include <iostream>#define MAX_VERTEX_NUM 100#define INF 1<<16using namespace std;typedef struct{    char V[MAX_VERTEX_NUM]; //顶点    int A[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //邻接矩阵}MGraph;typedef struct{    int node;    string name;}Point;void Floyd(MGraph* G,int path[][MAX_VERTEX_NUM],int D[][MAX_VERTEX_NUM],int n){    //初始化    for(int i = 0;i < n;i++)    {        for(int j = 0;j < n;j++)        {            if(G->A[i][j] < INF)            {                path[i][j] = j;            }            else            {                path[i][j] = -1;            }            D[i][j] = G->A[i][j];        }    }    //Floyd    for(int k = 0;k < n;k++){        for(int i = 0;i < n;i++){            for(int j = 0;j < n;j++){                if(D[i][j] > D[i][k] + D[k][j])                {                    D[i][j] = D[i][k] + D[k][j];                    path[i][j] = path[i][k];                }            }        }    }}int main(){    int n;    int path[MAX_VERTEX_NUM][MAX_VERTEX_NUM];    int D[MAX_VERTEX_NUM][MAX_VERTEX_NUM];    MGraph G;    cout << "Please input the number of vertex:";    cin >> n;    Point point[MAX_VERTEX_NUM];    for(int i;i < n;i++)    {        printf("Please input %d st vertex's name:", i);        point[i].node = i;        cin >> point[i].name;    }    cout << "Please input the adjacent matrix:" << endl;    int a[MAX_VERTEX_NUM][MAX_VERTEX_NUM];    for(int i = 0;i < n;i++)    {        for(int j = 0;j < n;j++)        {            cin >> a[i][j];            G.A[i][j] = a[i][j];        }    }    Floyd(&G, path, D, n);    string sp,dp;    int s,d;    cout << "Please input the project:";    cin >> sp >> dp;    for (int i = 0;i < n;i++)        if(sp == point[i].name)            s = point[i].node;    for (int i = 0;i < n;i++)        if(dp == point[i].name)            d = point[i].node;    printf("%d\t",D[s][d]);    int k = path[s][d];    if(k == -1)    {        printf("There is no path between V%d and V%d\n",s,d);    }    else    {        printf("最短路径为:");        cout << "(" << sp;        while(k != d)        {            cout << "," << point[k].name;            k = path[k][d];        }        cout << "," << dp << ")";    }    return 0;}
0 0