首页 > 解决方案 > 如何在 c 中使用 Dijkstra 的最短路径打印路径?

问题描述

我正在开发一个打印距离和路径的程序。我的距离运行良好,但是当我尝试打印路径时出现了问题。我尝试了很多导致分段错误或仅打印 MAX_INT 的方法。现在它只是向后打印权重最短的节点,无论节点是否在路径中。

这是代码,附件将是一个图表,请注意,我将对其进行更改以接收源和目标的用户输入,但对我来说,我只是测试代码,我刚刚将源 0 和目标设为 4。另外附上一张图表的照片。 图形

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct AdjListNode
{
    int dest;
    int weight;
    struct AdjListNode* next;
};

struct AdjList
{
    struct AdjListNode *head;  // pointer to head node of list
};

struct Graph
{
    int V;
    struct AdjList* array;
};

struct AdjListNode* newAdjListNode(int dest, int weight)
{
    struct AdjListNode* newNode =
            (struct AdjListNode*) malloc(sizeof(struct AdjListNode));
    newNode->dest = dest;
    newNode->weight = weight;
    newNode->next = NULL;
    return newNode;
}

struct Graph* createGraph(int V)
{
    struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
    graph->V = V;

    // Create an array of adjacency lists.  Size of array will be V
    graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));

     // Initialize each adjacency list as empty by making head as NULL
    for (int i = 0; i < V; ++i)
        graph->array[i].head = NULL;

    return graph;
}

void addEdge(struct Graph* graph, int src, int dest, int weight)
{
    // Add an edge from src to dest.  A new node is added to the adjacency
    // list of src.  The node is added at the begining
    struct AdjListNode* newNode = newAdjListNode(dest, weight);
    newNode->next = graph->array[src].head;
    graph->array[src].head = newNode;

    // Since graph is undirected, add an edge from dest to src also
    newNode = newAdjListNode(src, weight);
    newNode->next = graph->array[dest].head;
    graph->array[dest].head = newNode;
}

struct MinHeapNode
{
    int  v;
    int dist;
    struct MinHeapNode *parent;
};

struct MinHeap
{
    int size;      // Number of heap nodes present currently
    int capacity;  // Capacity of min heap
    int *pos;     // This is needed for decreaseKey()
    struct MinHeapNode **array;
};

struct MinHeapNode* newMinHeapNode(int v, int dist)
{
    struct MinHeapNode* minHeapNode =
           (struct MinHeapNode*) malloc(sizeof(struct MinHeapNode));
    minHeapNode->v = v;
    minHeapNode->dist = dist;
    return minHeapNode;
}

struct MinHeap* createMinHeap(int capacity)
{
    struct MinHeap* minHeap =
         (struct MinHeap*) malloc(sizeof(struct MinHeap));
    minHeap->pos = (int *)malloc(capacity * sizeof(int));
    minHeap->size = 0;
    minHeap->capacity = capacity;
    minHeap->array =
         (struct MinHeapNode**) malloc(capacity * sizeof(struct MinHeapNode*));
    return minHeap;
}

void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
{
    struct MinHeapNode* t = *a;
    *a = *b;
    *b = t;
}

void minHeapify(struct MinHeap* minHeap, int idx)
{
    int smallest, left, right;
    smallest = idx;
    left = 2 * idx + 1;
    right = 2 * idx + 2;

    if (left < minHeap->size &&
        minHeap->array[left]->dist < minHeap->array[smallest]->dist )
      smallest = left;

    if (right < minHeap->size &&
        minHeap->array[right]->dist < minHeap->array[smallest]->dist )
      smallest = right;

    if (smallest != idx)
    {
        MinHeapNode *smallestNode = minHeap->array[smallest];
        MinHeapNode *idxNode = minHeap->array[idx];

        minHeap->pos[smallestNode->v] = idx;
        minHeap->pos[idxNode->v] = smallest;

        swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);

        minHeapify(minHeap, smallest);
    }
}

int isEmpty(struct MinHeap* minHeap)
{
    return minHeap->size == 0;
}

struct MinHeapNode* extractMin(struct MinHeap* minHeap)
{
    if (isEmpty(minHeap))
        return NULL;

    struct MinHeapNode* root = minHeap->array[0];

    struct MinHeapNode* lastNode = minHeap->array[minHeap->size - 1];
    minHeap->array[0] = lastNode;

    minHeap->pos[root->v] = minHeap->size-1;
    minHeap->pos[lastNode->v] = 0;

    --minHeap->size;
    minHeapify(minHeap, 0);

    return root;
}

void decreaseKey(struct MinHeap* minHeap, int v, int dist)
{
    int i = minHeap->pos[v];

    minHeap->array[i]->dist = dist;

    while (i && minHeap->array[i]->dist < minHeap->array[(i - 1) / 2]->dist)
    {
        minHeap->pos[minHeap->array[i]->v] = (i-1)/2;
        minHeap->pos[minHeap->array[(i-1)/2]->v] = i;
        swapMinHeapNode(&minHeap->array[i],  &minHeap->array[(i - 1) / 2]);

        i = (i - 1) / 2;
    }
}

bool isInMinHeap(struct MinHeap *minHeap, int v)
{
   if (minHeap->pos[v] < minHeap->size)
     return true;
   return false;
}

void printLength(int dist[], int n,int des)
{

    printf("LENGTH: %d",dist[des]);

}

void printPath (struct MinHeapNode *last, int source,int des)
{
    printf ("\nPATH\n");
    while (last != NULL)
    {
        printf ("%d ,  ", last->v);

        last = last->parent;
    }


}

void dijkstra(struct Graph* graph, int src, int des)
{
    int V = graph->V;// Get the number of vertices in graph
    int dist[V];      // dist values used to pick minimum weight edge in cut

    // minHeap represents set E
    struct MinHeap* minHeap = createMinHeap(V);

    // Initialize min heap with all vertices. dist value of all vertices
    for (int v = 0; v < V; ++v)
    {
        //parent[0]= -1;
        dist[v] = INT_MAX;
        minHeap->array[v] = newMinHeapNode(v, dist[v]);
        minHeap->pos[v] = v;
    }

    // Make dist value of src vertex as 0 so that it is extracted first
    minHeap->array[src] = newMinHeapNode(src, dist[src]);
    minHeap->pos[src] = src;
    dist[src] = 0;
    decreaseKey(minHeap, src, dist[src]);

    // Initially size of min heap is equal to V
    minHeap->size = V;

    struct MinHeapNode *prev = NULL;
    // In the followin loop, min heap contains all nodes
    // whose shortest distance is not yet finalized.
    while (!isEmpty(minHeap))
    {
        // Extract the vertex with minimum distance value
        struct MinHeapNode* minHeapNode = extractMin(minHeap);
        minHeapNode->parent = prev;
        prev = minHeapNode;

        int u = minHeapNode->v; // Store the extracted vertex number

        // Traverse through all adjacent vertices of u (the extracted
        // vertex) and update their distance values
        struct AdjListNode* pCrawl = graph->array[u].head;
        while (pCrawl != NULL)
        {
            int v = pCrawl->dest;

            // If shortest distance to v is not finalized yet, and distance to v
            // through u is less than its previously calculated distance
            if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
                pCrawl->weight + dist[u] < dist[v])
            {

                dist[v] = dist[u] + pCrawl->weight;


                // update distance value in min heap also
                decreaseKey(minHeap, v, dist[v]);


            }
            pCrawl = pCrawl->next;
        }
    }

    // print the calculated shortest distances
    printLength(dist, src,des);
    printPath(prev,src,des);


}
int main() 
{ 
    // create the graph given in above fugure 
    int V = 9; 
    struct Graph* graph = createGraph(V); 
    addEdge(graph, 0, 1, 4); 
    addEdge(graph, 0, 7, 8); 
    addEdge(graph, 1, 2, 8); 
    addEdge(graph, 1, 7, 11); 
    addEdge(graph, 2, 3, 7); 
    addEdge(graph, 2, 8, 2); 
    addEdge(graph, 2, 5, 4); 
    addEdge(graph, 3, 4, 9); 
    addEdge(graph, 3, 5, 14); 
    addEdge(graph, 4, 5, 10); 
    addEdge(graph, 5, 6, 2); 
    addEdge(graph, 6, 7, 1); 
    addEdge(graph, 6, 8, 6); 
    addEdge(graph, 7, 8, 7); 

    dijkstra(graph, 0,4); 

    return 0; 
} 

标签: cdijkstra

解决方案


在 Dijkstra 的算法中,您将新节点(最短的腿)添加到已访问的节点集中,直到您将目的地包含在其中。假设您在 中包含一个字段prev(指向节点的指针)struct AdjListNode,只要您将节点包含在一组已经可到达的节点中,当您添加节点时,您就可以使该指针指向它所附加的节点到可达节点集。只要它所附加的节点已经被添加,它的prev节点就会指向它所附加的节点......等等。第一个节点(出发节点)只是不指向任何地方(它是NULL,因为它从未被标记——当你开始时它已经在集合中),所以你有到源节点的反向路径,通过跟随指针prev从每个访问的节点到原点。您可以编写这样的子例程:

void print_path(struct AdjListNode *nod, FILE *out)
{
    /* recurse until the origin */
    if (nod->prev) {
        print_path(nod->prev, out);
        fprintf(out, "->"); /* separator */
    }
    fprintf(out, "d=%5(w=%d)", 
         nod->dest, nod->weight);
}

该指针非常有用,因为对于每个访问的节点,它都存储通过最短路径到原点的路由,而不仅仅是您感兴趣的节点。

笔记

我没有检查你的实现,因为你说你的问题只是找到到目的地的实际路线,所以我不会包括你修补的代码。我只是把它留给你,作为练习。我只是给你一个提示,而不是解决你的作业。对此我深表歉意。

第二注

我已经编写了该算法的完整实现。正如您在评论中指出的那样,这可能会很好地翻译成 C++,您应该需要它。它由三个文件组成,main.c(主程序)、dijkstra.h(带有结构定义的头文件)和dijkstra.c(实现)它可以在这里找到


推荐阅读