本文共 1379 字,大约阅读时间需要 4 分钟。
感谢“乐观的阿锡”博主分享了K最短路径算法的相关内容。在学习过程中,Dijkstra算法是一个非常实用的工具。为了方便使用,我们将其模块化实现,并注明出处以便引用。
Dijkstra算法,由Leonhard Euler提出的,它以其提出者的人名命名。理论部分可参考教材《最优化技术与数学建模》(董文永等编,清华大学出版社,2010年)。该算法代码已实现模块化处理,可直接调用。
代码注释:
代码实现:
function [pathout cost] = dijkstra(netCostMatrix, source, destination) if ~is-empty(destination) return [pathout cost] else return [destination_col, permanent_number] end m = size(netCostMatrix, 1); n = size(netCostMatrix, 2); cost = ones(m, 1); distance = inf * ones(m, 1); distance(source) = 0; pathnode = zeros(m, 1); count = 1; while count <= m u = find(min(distance), 1); if distance(u) < cost(u) cost(u) = distance(u); pathnode(u) = 0; else pathnode(u) = 0; end for v = 1:m if netCostMatrix(u,v) == inf continue; end if distance(v) > cost(u) + netCostMatrix(u, v) distance(v) = cost(u) + netCostMatrix(u, v); pathnode(v) = u; end if distance(v) == cost(u) + netCostMatrix(u, v) ... end end count = count + 1; end if ~is-empty(destination) ... endend
代码注释已完毕,为开发者提供清晰的使用指南。
转载地址:http://txdjz.baihongyu.com/