matlab实现dijkstra算法
时间: 2023-09-13 18:07:48 浏览: 43
以下是 MATLAB 实现 Dijkstra 算法的示例代码:
```matlab
function [D, P] = dijkstra(G, s)
% DIJKSTRA - Dijkstra's shortest path algorithm
% [D, P] = DIJKSTRA(G, s) returns the shortest distance D from s to all
% other nodes and the path P from s to each of the other nodes in the
% directed graph G represented by an adjacency matrix.
%
% Written by W.-Y. Chen and C.-H. Shen, 2010
% Modified by X.-Y. Li, 2012
n = size(G, 1); % number of nodes
D = Inf(1, n); % initialize distances
D(s) = 0;
P = zeros(n, n);
for i = 1:n
if G(s, i) ~= Inf
P(i, :) = G(s, :);
end
end
S = 1:n; % set of nodes whose shortest path is not yet known
while ~isempty(S)
[d, u] = min(D(S)); % find the node with the smallest distance
if isinf(d)
break;
end
S(u) = []; % remove the node from S
for v = 1:n
if ~ismember(v, S) || G(u, v) == Inf
continue;
end
if D(u) + G(u, v) < D(v)
D(v) = D(u) + G(u, v);
P(v, :) = P(u, :);
P(v, v) = 1;
end
end
end
```
在这个算法中,G 是一个 n x n 的邻接矩阵,表示有向图中每个节点之间的距离。s 是源节点的索引。该算法返回的 D 是一个包含源节点到其他每个节点的最短路径的数组,P 是一个包含从源节点到其他每个节点的路径的数组。