繁体   English   中英

使用邻接矩阵的dijkstra算法

[英]dijkstra's algorithm using adjacency matrix

我目前正在尝试为Dijkstras算法创建程序。 我在理解如何为算法创建图形时遇到麻烦。

我在将其实现为图形时遇到麻烦。

我想创建一个名为

add_edge(G, Source, destination, weight);

我想使用此功能创建图形,以便以后可以创建随机图形。 例如,我会这样做:

add_edge(G,1,2,3);
add_edge(G,1,6,5);
add_edge(G,2,3,7);
etc.

我想做的第一件事是创建G,但是我不确定该怎么做。 我正在考虑使另一个函数称为构造,它等于G,例如:

G = construct(Vertices);

我只是不确定如何构造它。

如果有人可以帮助我理解这两个功能,那将是很大的帮助!

这是制作整数的nx x ny数组的一种方法:

int **construct(int nx, int ny) {
    int **a = malloc(nx * sizeof(*a));
    for(int i = 0; i != ny; i++) {
        a[i] = calloc(ny, sizeof(int));
    }
    return a;
}

什么是G ...? G是您的graph吗? 还是G是用来表示图形的matrix 拥有如下所示的东西(伪)是最有意义的:

// This is your graph, represented by a 2-d array.
// i would be your source (vertex)
// j would be your destination (vertex)
// graph[i][j] would be the weight of the edge between those two points

int graph[][];

// Then you could add an edge to your graph with the following:

add_edge(graph, source, destination, weight) {
  graph[source][destination] = weight;
}

// A specific example would be:

add_edge(graph, 10, 11, 5)

尽管您需要知道:C中的2-d数组实际上是类型为p的指针的数组。

所以int **graph;

有关如何(具体地)创建一个matrix of ints请参见Charlie的答案。

如果要使用矩阵制作图形,请使用上述答案。 否则,如果您要使用结构构建它,也许像这样的事情可能会让您入门

typedef struct VertexT *VertexP;
struct VertexT
{
     /*the value of the current Vertex*/
     int vertex;

     /*pointer to a list of edges, each value being an end point since this
     is a directed graph*/
     EdgeP edges;

     /*pointer to a list of weights, each weight corresponding to each edge
     thus there should be an equal number of items in both lists or there
     is an error condition*/
     WeightP weights;
}

typedef struct GraphT *GraphP;
struct GraphT
{
     /*pointer to a list of vertices in the graph, should contain exactly
     n vertices, where n is the number of nodes in the graph*/
     VertexP vertices;
}

这绝不是实现此目的的唯一方法,但是我想提供一种struct方法作为使用严格矩阵的替代方法。 如果它是稀疏图,则使用列表可以优化空间复杂度,而不是使用矩阵。 希望能帮助您入门。

注意:我使用typedef是因为我发现使用VertexP或GraphP比struct * VertexT和struct * GraphT更容易阅读和理解,它的风格比其他任何东西都重要。

刚刚看到了有关addEdge()函数的编辑。 如果您要使用我的表示形式,则可以将伪代码看作是这样的:

addEdge(GraphP g, int source, int dest, int weight)
     test for g being null:
          if true, create a graph or throw exception
          if false, continue
     search for source in VertexP list:
          if true, 
               search for dest in edges
                    if true report error
                    if false add new edge and weight to list on the source VertexP
          if false, create new VertexP with source, dest, weight and add to list

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM