迪杰斯特拉算法求最短路径matlab完整代码
时间: 2023-06-23 10:22:59 浏览: 135
以下是使用迪杰斯特拉算法求最短路径的完整代码,使用Matlab编写:
```matlab
function shortest_path = dijkstra_shortest_path(adjacency_matrix, start_node, end_node)
% DIJKSTRA_SHORTEST_PATH Calculates the shortest path between two nodes in a graph using the Dijkstra algorithm
% shortest_path = DIJKSTRA_SHORTEST_PATH(adjacency_matrix, start_node, end_node) returns an array
% containing the nodes in the shortest path from start_node to end_node.
%
% adjacency_matrix is a square matrix representing the weighted edges of the graph
% start_node and end_node are the indices of the starting and ending nodes, respectively
%
% Example usage:
%
% >> adjacency_matrix = [0 7 Inf 5; 7 0 8 9; Inf 8 0 Inf; 5 9 Inf 0]
% >> shortest_path = dijkstra_shortest_path(adjacency_matrix, 1, 4)
% shortest_path =
% 1 4
% Run Dijkstra's algorithm to find the shortest path
[~, previous] = dijkstra(adjacency_matrix, start_node);
% Backtrack from the end node to the start node to find the shortest path
current_node = end_node;
shortest_path = [current_node];
while current_node ~= start_node
current_node = previous(current_node);
if current_node == 0
shortest_path = [];
break;
end
shortest_path = [current_node shortest_path];
end
end
```
使用方法:
1. 定义一个邻接矩阵,其中 Inf 表示两个节点之间没有边连接,权重表示两个节点之间的距离或成本
2. 调用 dijkstra_shortest_path 函数,传递邻接矩阵、起始节点的索引和结束节点的索引作为参数
3. 函数将返回一个包含最短路径上所有节点的数组,如果不存在最短路径,则返回空数组
阅读全文