簡體   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