dijkstra算法的matlab实现
时间: 2023-11-13 11:54:01 浏览: 89
【老生谈算法】Dijkstra算法matlab实现.docx
以下是dijkstra算法的matlab实现:
```matlab
function [dist, path] = dijkstra_algorithm(adj_matrix, start_node, end_node)
% adj_matrix: 邻接矩阵
% start_node: 起始节点
% end_node: 终止节点
% dist: 起始节点到各个节点的最短距离
% path: 起始节点到各个节点的最短路径
n = size(adj_matrix, 1);
dist = inf(1, n);
path = cell(1, n);
visited = false(1, n);
dist(start_node) = 0;
path{start_node} = num2str(start_node);
for i = 1:n-1
[~, u] = min(dist(~visited));
visited(u) = true;
for v = 1:n
if ~visited(v) && adj_matrix(u, v) ~= 0 && dist(u) + adj_matrix(u, v) < dist(v)
dist(v) = dist(u) + adj_matrix(u, v);
path{v} = [path{u}, '->', num2str(v)];
end
end
end
if isempty(path{end_node})
path{end_node} = 'No path found';
end
end
```
阅读全文