我们一直在做一个机器人在房间里行驶的项目,当我们激活它时,它会返回到一个选定的目的地。我们的任务是找到到达该目的地的最短路径。
我们一直在用 C 编码,并尝试使用 Dijkstra 的算法,但我们现在有点卡住了。我们没有得到最短的路线。weights 中的第一个位置是起始坐标,end 是最后一个。
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。
希望有人能看到我们缺少的东西。