请编写一个可在matlab2021运行的Dijkstra算法
时间: 2024-05-04 11:17:18 浏览: 54
好的,以下是一个基于 MATLAB 实现的 Dijkstra 算法:
```matlab
function [dist, path] = dijkstra(adj_matrix, start_node, end_node)
% DIJKSTRA Compute the shortest path between two nodes in a graph using Dijkstra algorithm.
%
% Input:
% - adj_matrix: A n-by-n matrix represents the adjacency matrix of the graph.
% adj_matrix(i, j) = the weight of the edge between node i and node j.
% If there is no edge between node i and node j, adj_matrix(i, j) = inf.
% - start_node: The index of the starting node.
% - end_node: The index of the ending node.
%
% Output:
% - dist: A scalar represents the shortest distance between the start_node and end_node.
% - path: A vector represents the path from the start_node to the end_node.
n = size(adj_matrix, 1); % Number of nodes in the graph
visited = false(n, 1); % Visited flag
dist = inf(n, 1); % Distance from start_node to each node
prev = zeros(n, 1); % Previous node in the shortest path
dist(start_node) = 0; % Distance from start_node to start_node is 0
for i = 1:n
% Find the node with the smallest distance
[~, u] = min(dist(~visited));
if isempty(u)
break;
end
visited(u) = true;
if u == end_node
break;
end
% Update the distance of the neighboring nodes
for v = 1:n
if ~visited(v) && adj_matrix(u, v) < inf
alt = dist(u) + adj_matrix(u, v);
if alt < dist(v)
dist(v) = alt;
prev(v) = u;
end
end
end
end
% Compute the path from start_node to end_node
path = [];
u = end_node;
while prev(u) ~= 0
path = [u, path];
u = prev(u);
end
if ~isempty(path)
path = [start_node, path];
end
end
```
使用方法:
假设我们有一个 5 个节点的图,其邻接矩阵为:
```
0 4 1 ∞ ∞
4 0 3 2 ∞
1 3 0 4 2
∞ 2 4 0 3
∞ ∞ 2 3 0
```
我们想要计算从节点 1 到节点 5 的最短路径,可以使用以下代码:
```matlab
adj_matrix = [0 4 1 inf inf;
4 0 3 2 inf;
1 3 0 4 2;
inf 2 4 0 3;
inf inf 2 3 0];
[start_node, end_node] = deal(1, 5);
[dist, path] = dijkstra(adj_matrix, start_node, end_node);
```
其中 `dist` 是从起点到每个节点的最短距离,`path` 是从起点到终点的最短路径。
阅读全文