图的最短路径Dijkstra算法

算法核心

当前顶点V到其他点距离的最小值即为V到此顶点的最小路径,这是一种贪心思想。

/*
5 7
0 1 10
0 3 30
0 4 100
1 2 50
2 4 10
3 2 20
3 4 60
0 2
*/
#include<iostream>
#include<cstdio>
using namespace std;
struct MGraph
{
    int arc[100][100];  //假设最多一百个顶点:
    int n,e;  //顶点,边的个数;
    MGraph(int x,int y)
    {
        int i,j,k,t;
        n=x;e=y;
        for(i=0;i<n;i++)
            for(j=0;j<n;j++)
                arc[i][j]=9999;    //初始化为9999;
        for(k=0; k<e; k++)
        {
            cin>>i>>j>>t;
            arc[i][j]=t;
        }
    }
};
void Dijkstra(MGraph M,int v,int s[])  //在图M中,顶点v到其他顶点的最小路径;
{
    int dist[100];                     //存放v到其他顶点目前的最小路径;
    int i,k,curentmin,t,j;
    s[v]=0;                            //s存放最小路径;
    for(i=0;i<M.n;i++)
        dist[i]=M.arc[v][i];
    dist[v]=0;                          //它到本身的距离为0;
    i=1;
    while(i<M.n)
    {
        curentmin=9999;
        for(j=0;j<M.n;j++)
            if(dist[j]!=0&&dist[j]<curentmin) {curentmin=dist[j];k=j;}

        s[k]=curentmin;
        for(t=0;t<M.n;t++)
            if(dist[t]>dist[k]+M.arc[k][t])
            dist[t]=dist[k]+M.arc[k][t];
            dist[k]=0;
            i++;
    }
}
int main()
{
    int s[100],n,e;
    int start,end;
    cin>>n>>e;
    MGraph M(n,e);
    cin>>start>>end;
    Dijkstra(M,start,s);
    cout<<s[end]<<endl;
    return 0;
}

测试数据:

第一行 顶点数(n)  边数(e)

第二行到第e+1行 录入三个数据分别为 start end weight

第e+2行  需要求的起始点和终点

/*
5 7
0 1 10
0 3 30
0 4 100
1 2 50
2 4 10
3 2 20
3 4 60
0 4

*/

截图:



猜你喜欢

转载自blog.csdn.net/qq_40458569/article/details/80512800
今日推荐