如何在 c 中使用 Dijkstra 的最短路径打印路径?
How do I print the path using Dijkstra's shortest path in c?
我正在开发一个打印距离和路径的程序。我的距离工作得很好,但是当我尝试打印路径时,我遇到了问题。我尝试了很多导致分段错误或只是打印 MAX_INT 的事情。现在它只是向后打印权重最短的节点,而不管该节点是否在路径中。
这是代码并附上一张图表,请注意我将对此进行更改以接收用户输入的源和目标,但对我来说只是测试我刚刚将源 0 和目的地 4. 还附上了图表的照片。
GRAPH
#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;
}
查看代码,我很确定主要问题是您实际上没有实现 Dijkstra 算法。
特别是,您不需要遍历所有节点(这是您当前正在做的)。相反,从头开始,您将沿着尽可能短的路径到达目的地。
一开始,您只将一个节点放入您的 minHeap:距离为 0 的起始节点。
你的循环应该从堆中取出顶部元素,检查它是否是目标。如果是,则中断。否则将所有未访问的邻居及其各自的距离(当前节点的距离+边缘权重)放入最小堆。
在此遍历过程中,为每个访问的节点存储您来自的节点是有意义的。这允许您在到达目的地后返回原路。
话虽这么说:我也对你的最小堆有疑问。我不确定你在那里做什么,但是一旦最小堆的用户开始按索引访问元素,设计肯定会被破坏。
向后打印路径的伪代码:
v = end_node
while v != start_node
print(v)
v = adjacent node for which a sum: distance + edge_weight(v,adjacent) is minimum
print (v) // print start node
这是基于 dist + edge_weight
最小的边在路径上的观察(当向后看时)。
在 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
(实现)可用here.
我正在开发一个打印距离和路径的程序。我的距离工作得很好,但是当我尝试打印路径时,我遇到了问题。我尝试了很多导致分段错误或只是打印 MAX_INT 的事情。现在它只是向后打印权重最短的节点,而不管该节点是否在路径中。
这是代码并附上一张图表,请注意我将对此进行更改以接收用户输入的源和目标,但对我来说只是测试我刚刚将源 0 和目的地 4. 还附上了图表的照片。 GRAPH
#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;
}
查看代码,我很确定主要问题是您实际上没有实现 Dijkstra 算法。
特别是,您不需要遍历所有节点(这是您当前正在做的)。相反,从头开始,您将沿着尽可能短的路径到达目的地。
一开始,您只将一个节点放入您的 minHeap:距离为 0 的起始节点。
你的循环应该从堆中取出顶部元素,检查它是否是目标。如果是,则中断。否则将所有未访问的邻居及其各自的距离(当前节点的距离+边缘权重)放入最小堆。
在此遍历过程中,为每个访问的节点存储您来自的节点是有意义的。这允许您在到达目的地后返回原路。
话虽这么说:我也对你的最小堆有疑问。我不确定你在那里做什么,但是一旦最小堆的用户开始按索引访问元素,设计肯定会被破坏。
向后打印路径的伪代码:
v = end_node
while v != start_node
print(v)
v = adjacent node for which a sum: distance + edge_weight(v,adjacent) is minimum
print (v) // print start node
这是基于 dist + edge_weight
最小的边在路径上的观察(当向后看时)。
在 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
(实现)可用here.