Dijkstra算法的matlab实现
时间: 2023-11-12 16:57:22 浏览: 71
基于matlab实现Dijkstra算法.zip
以下是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 adj_matrix(u, v) ~= 0 && ~visited(v)
alt = dist(u) + adj_matrix(u, v);
if alt < dist(v)
dist(v) = alt;
path{v} = [path{u}, '->', num2str(v)];
end
end
end
end
if isempty(path{end_node})
path{end_node} = 'No path found';
end
end
```
阅读全文