将加权边实现为图形

Implementing Weighted edges to graph

我希望能够实现最短路径算法,但我意识到实际边本身没有权重。我想改变我的结构,这样我就可以为从一个顶点到另一个顶点的权重取一个数值。我将如何实施?

#include<stdio.h>
    #include<stdlib.h>
    struct edge
    {
        int vertexIndex;
        struct edge *edgePtr;
    }edge;
    struct vertex
    {
        int vertexKey;
        struct edge *edgePtr;
    }vertex;
    struct vertex graph[1000];
    int vertexCount=0;
    void InsertVertex(int vertexKey)
    {
        graph[vertexCount].vertexKey=vertexKey;
        graph[vertexCount].edgePtr=NULL;
        vertexCount++;
    }
    void insertEdge(int vertex1, int vertex2)
    {
        struct edge *e,*e1,*e2;
        e=graph[vertex1].edgePtr;
        while(e&& e->edgePtr)
        {
            e=e->edgePtr;
        }
        e1=(struct edge *)malloc(sizeof(*e1));
        e1->vertexIndex=vertex2;
        e1->edgePtr=NULL;
        if(e)
            e->edgePtr=e1;
        else
            graph[vertex1].edgePtr=e1;
        e=graph[vertex2].edgePtr;
        while(e&& e->edgePtr)
        {
            e=e->edgePtr;
        }
        e2=(struct edge *)malloc(sizeof(*e2));
        e2->vertexIndex=vertex1;
        e2->edgePtr=NULL;
        if(e)
            e->edgePtr=e2;
        else
            graph[vertex2].edgePtr=e2;
    }
    void printGraph()
    {
        int i;
        struct edge *e;
        for(i=0;i<vertexCount;i++)
        {
            printf("%d",i);
            e=graph[i].edgePtr;
            while(e)
            {
                printf("->%d",e->vertexIndex);
                e=e->edgePtr;
            }
            printf("\n");
        }
    }
    int main()
    {
        InsertVertex(1);
        InsertVertex(2);
        InsertVertex(3);
        InsertVertex(4);
        InsertVertex(5);
        insertEdge(0,1);
        insertEdge(0,2);
        insertEdge(1,3);
        insertEdge(1,4);
        insertEdge(3,5);
        printGraph();
        return 0;
    }

权重是边的一个属性,因此您可以将其添加到边结构中。

struct edge
{
   // You can use "-1" as the default invalid weight
   int weight;
   int vertexIndex;
   struct edge *edgePtr;
}edge;