获取最短距离 - GetShortestDistance
函数简介
在指定的图中计算从起点到终点的最短距离,使用Dijkstra算法实现。
接口名称
GetShortestDistance
DLL调用
double GetShortestDistance(int64_t instance, int64_t graphPtr, char* from, char* to);
参数说明
参数名 | 类型 | 说明 |
---|---|---|
instance | 长整数型 | OLAPlug对象的指针,由 CreateCOLAPlugInterFace 接口生成。 |
graphPtr | 长整数型 | 图的指针,由CreateGraph接口返回 |
from | 字符串 | 起点节点名称 |
to | 字符串 | 终点节点名称 |
示例
// 创建OLA实例
int64_t instance = CreateCOLAPlugInterFace();
// 创建图并添加边
int64_t graphPtr = CreateGraph(instance, "");
AddEdge(instance, graphPtr, "A", "B", 1.0, false);
AddEdge(instance, graphPtr, "B", "C", 2.0, false);
AddEdge(instance, graphPtr, "C", "D", 1.0, false);
AddEdge(instance, graphPtr, "A", "D", 5.0, false);
// 获取从A到D的最短距离
double distance = GetShortestDistance(instance, graphPtr, "A", "D");
if (distance >= 0) {
printf("最短距离: %.2f\n", distance);
} else {
printf("未找到路径\n");
}
// 释放资源
DeleteGraph(instance, graphPtr);
DestroyCOLAPlugInterFace(instance);
返回值
返回从起点到终点的最短距离(双精度浮点数)。如果不存在路径返回-1。
注意事项
- 距离是路径上所有边权重的总和
- 如果两点间不存在路径,函数返回-1
- 确保from和to节点在图中存在
- 算法会考虑边的权重,寻找总权重最小的路径
- 对于无向图,from到to的距离等于to到from的距离