matlab中Dijkstra算法代码
时间: 2023-08-08 10:08:02 浏览: 112
以下是使用MATLAB实现Dijkstra算法的代码:
```matlab
function [distances, path] = dijkstra_algorithm(adjacency_matrix, start_node, end_node)
% Dijkstra算法的MATLAB实现
% adjacency_matrix: 邻接矩阵
% start_node: 起始节点
% end_node: 终止节点
% distances: 从起始节点到每个节点的最短距离
% path: 从起始节点到终止节点的最短路径
num_nodes = size(adjacency_matrix, 1); % 节点数
distances = inf(1, num_nodes); % 到每个节点的距离
visited = false(1, num_nodes); % 是否访问过
distances(start_node) = 0;
for i = 1:num_nodes
% 找到未访问过的距离最小的节点
min_distance = inf;
current_node = -1;
for j = 1:num_nodes
if ~visited(j) && distances(j) < min_distance
min_distance = distances(j);
current_node = j;
end
end
if current_node == -1
break;
end
visited(current_node) = true;
% 更新与当前节点相邻的节点的距离
for j = 1:num_nodes
if adjacency_matrix(current_node, j) ~= 0
new_distance = distances(current_node) + adjacency_matrix(current_node, j);
if new_distance < distances(j)
distances(j) = new_distance;
path(j) = current_node;
end
end
end
end
% 构建路径
path = [];
current_node = end_node;
while current_node ~= start_node
path = [current_node, path];
current_node = path(current_node);
end
path = [start_node, path];
end
```
其中,`adjacency_matrix`为邻接矩阵,`start_node`为起始节点,`end_node`为终止节点。函数返回`distances`为从起始节点到每个节点的最短距离,`path`为从起始节点到终止节点的最短路径。
阅读全文