问题::已为我提供了一张全国范围内的点地图,负责从一个目的地到另一个目的地(查找最短路线)。我已经研究djikstra的算法几天了,但是我仍然不知道如何将其转换为可运行的代码。
我创建了一个带有适当位置的2D图形,并创建了一个调用函数,该函数应该以递归方式完成程序,我希望我能对如何解决问题有所了解此作业。
代码:
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
#define VERT 14
int minDist(int dist[], bool sptSet[]) // a function to find the node with minimum distance value from the set of
//vertices not included in the shortest path tree.
{
int min = INT_MAX, min_index, i = 0;
for (; i < VERT; i++)
if (sptSet[i] == false && dist[i] <= min) {
min = dist[i];
min_index = i;
}
return min_index;
}
void printFinal(int dist[], int n) {
printf("Node Distance from source\n");
for (int i = 0; i < n; i++) {
printf("%d\n", i);
printf("%d\n", dist[i]);
}
}
void travelPath(int map[VERT][VERT], int start) {
int distance[VERT];//The output array. dist[i] will hold the shortest distance from src to i
bool sptSet[VERT]; // sptSet[i] will true if vertex i is included in shortest
//path tree or shortest distance from src to i is finalized
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < VERT; i++) {
distance[i] = INT_MAX;
sptSet[i] = false;
}
// Distance of source vertex from itself is always 0
distance[start] = 0;
for (int count = 0; count < VERT - 1; count++) {
int u = minDist(distance, sptSet); // Pick the minimum distance vertex from the set of vertices not
//yet processed. u is always equal to src in first iteration.
sptSet[u] = true; // Mark the picked vertex as processed
for (int v = 0; v < VERT; v++) {
// Update dist[v] only if is not in sptSet, there is an edge from
// u to v, and total weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && map[u][v] && distance[u] != INT_MAX && distance[u] + map[u][v] < distance[v])
distance[v] = distance[u] + map[u][v];
}
printFinal(distance, VERT);
}
}
int main() {
//points on the map with zeroes representing infinity
int graph[VERT][VERT] = {{0, 808, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2060, 0},
{808, 0, 414, 0, 0, 0, 0, 0, 2257, 0, 0, 0, 0, 0},
{0, 414, 0, 1440, 0, 0, 0, 0, 0, 0, 0, 0, 0, 272},
{0, 0, 1440, 0, 517, 0, 0, 1614, 0, 949, 0, 0, 0, 0},
{0, 0, 0, 517, 0, 0, 0, 0, 0, 0, 0, 0, 1425, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1423, 0},
{0, 0, 0, 0, 0, 0, 0, 237, 811, 0, 0, 0, 0, 0},
{0, 0, 0, 1614, 0, 0, 237, 0, 0, 1217, 0, 0, 0, 0},
{0, 2257, 0, 0, 0, 0, 811, 0, 0, 0, 0, 1771, 0, 0},
{0, 0, 0, 949, 0, 0, 0, 1217, 0, 0, 797, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 792, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 1771, 0, 0},
{2060, 0, 0, 0, 948, 1423, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 272, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1780, 0}};
//passing to recursive function travelPath with the initial point
travelPath(graph, 0);
}
我很抱歉没有太多工作要做,这就是问题所在,我不了解如何在优雅地遍历地图的同时还使用递归...
感谢您提供的任何指导!
期望的输出:
Which two cities would you like to find the shortest routes between?
New York
San Francisco
New York --> Washington D.C.
Washington D.C. --> Milwaukee
Milwaukee --> San Francisco
The end!
编辑:添加了参考地图和更多代码。