matlab实现单源最短路径dijkstra算法
时间: 2023-12-09 08:36:59 浏览: 188
以下是Matlab实现单源最短路径Dijkstra算法的示例代码:
```matlab
function [dist, path] = dijkstra_algorithm(graph, start_node)
% graph: n*n的矩阵,表示有向图的邻接矩阵
% start_node: 起始节点
% dist: 1*n的向量,表示起始节点到各个节点的最短距离
% path: 1*n的向量,表示起始节点到各个节点的最短路径
n = size(graph, 1);
dist = inf(1, n); % 初始化距离为无穷大
path = zeros(1, n); % 初始化路径为0
visited = zeros(1, n); % 初始化所有节点为未访问
dist(start_node) = 0; % 起始节点到自身的距离为0
for i = 1:n
min_dist = inf;
min_node = -1;
for j = 1:n
if visited(j) == 0 && dist(j) < min_dist
min_dist = dist(j);
min_node = j;
end
end
if min_node == -1
break;
end
visited(min_node) = 1;
for j = 1:n
if visited(j) == 0 && graph(min_node, j) ~= inf && dist(min_node) + graph(min_node, j) < dist(j)
dist(j) = dist(min_node) + graph(min_node, j);
path(j) = min_node;
end
end
end
end
```
阅读全文