最短路径dijkstra算法matlab代码
时间: 2023-08-20 14:06:16 浏览: 122
Dijkstra和Floyd算法找最短路径matlab实现
5星 · 资源好评率100%
以下是Dijkstra算法的MATLAB代码示例:
```matlab
function [distances, paths] = Dijkstra(adjacencyMatrix, startNode)
% 获取节点数量
numNodes = size(adjacencyMatrix, 1);
% 初始化距离矩阵为无穷大
distances = inf(1, numNodes);
% 初始化路径矩阵
paths = cell(1, numNodes);
% 标记起始节点的距离为0
distances(startNode) = 0;
% 遍历所有节点
for i = 1:numNodes
% 寻找当前距离矩阵中最小的节点
[~, currentNode] = min(distances);
% 标记当前节点已访问
distances(currentNode) = NaN;
% 获取当前节点的邻居节点
neighbors = find(adjacencyMatrix(currentNode, :) > 0);
% 更新邻居节点的距离和路径
for j = 1:length(neighbors)
neighbor = neighbors(j);
% 计算从起始节点到邻居节点的距离
distance = distances(currentNode) + adjacencyMatrix(currentNode, neighbor);
% 如果新距离比当前距离小,则更新距离和路径
if distance < distances(neighbor)
distances(neighbor) = distance;
paths{neighbor} = [paths{currentNode}, neighbor];
end
end
end
end
```
此代码实现了Dijkstra算法,输入为邻接矩阵adjacencyMatrix和起始节点startNode,输出为距离矩阵distances和路径矩阵paths。请注意,此代码假设图中的节点从1到N编号。
阅读全文