获取最短路径 - GetShortestPath
函数简介
在指定的图中计算从起点到终点的最短路径,使用Dijkstra算法实现。
接口名称
GetShortestPath
DLL调用
int64_t GetShortestPath(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的最短路径
int64_t pathPtr = GetShortestPath(instance, graphPtr, "A", "D");
if (pathPtr != 0) {
printf("最短路径: %s\n", (char*)pathPtr);
// 释放返回的字符串内存
FreeStringPtr(pathPtr);
} else {
printf("未找到路径\n");
}
// 释放资源
DeleteGraph(instance, graphPtr);
DestroyCOLAPlugInterFace(instance);
返回值
返回最短路径的字符串指针,格式为:
"A|B|C|D"
如果不存在路径返回0。
注意事项
- 返回的字符串指针需要调用FreeStringPtr释放内存
- 确保from和to节点在图中存在
- 如果两点间不存在路径,函数返回0
- 路径按顺序返回从起点到终点的所有节点
- 算法会考虑边的权重,寻找总权重最小的路径