在C语言中实现Dijkstra算法问题

3

我们正在做一个机器人在房间里驾驶的项目,当我们激活它时,它会返回到一个选择的目的地。我们的任务是找到到达目的地最短的路径。

我们一直在用C语言编码,尝试使用Dijkstra算法,但现在有些卡住了。我们没有得到最短路线。权重中的第一个位置是起始坐标,最后一个位置是终点。

double dijkstras(double weights[MAX_ARRAY_SIZE][MAX_ARRAY_SIZE], char output[], int     *output_number_of_waypoints, int number_of_waypoints){ 

double route_length[number_of_waypoints];
int shortest_route_via[number_of_waypoints];

int i, current_pos;
double distance;
for (i = 0; i < number_of_waypoints; i++) {
    route_length[i] = 0;
    shortest_route_via[i] = -1;
}

int start = 0;                   /* first index in array */
int end = number_of_waypoints-1; /* last index in array */

for (current_pos = start; current_pos <= end; current_pos++) {
    for (i = 0; i < number_of_waypoints; i++) {
        if (weights[current_pos][i] > 0) {
            distance = route_length[current_pos] + weights[current_pos][i];
            if (distance < route_length[i] || shortest_route_via[i] == -1) {
                printf("shortest_route_via[%d] = current_pos = %d, length was %lf, shorted to %lf\n", i, current_pos, route_length[i], distance); /* debugging info */
                route_length[i] = distance;
                shortest_route_via[i] = current_pos;
            }
        }
    }
}
current_pos = end;
i = 0;
char route[number_of_waypoints+1];
while (current_pos != start && i < number_of_waypoints) {
    route[i] = current_pos;
    printf("currentpos = %d\n", current_pos); /* Debugging info - shortest path */
    current_pos = shortest_route_via[current_pos];
    i++;
}
route[i] = '\0';

return route_length[end];

我们想要得到一个数组shortest_route_via,其中包含最短路径通过的索引 - 例如 shortest_route_via[index] = waypoint。 route_length 包含前往该索引的成本,例如 route_length[index] = 100,表示前往索引需要花费100。

希望有人能看出我们漏掉了什么。

1个回答

3
如果我正确理解你的代码,你并没有真正使用Dijkstra算法。
Dijkstra从一个根节点开始,然后查看它可以到达的所有邻居。从根节点到所有邻居的距离被暂时设置。在下一次迭代中,最接近的暂时设置节点被设为永久节点,并将其邻居设为暂时节点。
你的代码没有选择最接近的节点。你只是按顺序遍历所有节点,通过递增current_pos的方式。除非最短路径在节点顺序上严格递增(索引仅按1->4->10->14->...的方式增加),否则你将无法获得保证的最短路径。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接