最短路径matlab代码
时间: 2023-11-25 12:36:47 浏览: 63
最短路径matlab代码实现
4星 · 用户满意度95%
以下是一个使用Dijkstra算法求解最短路径的MATLAB代码示例:
```matlab
function [distances, path] = dijkstra(adjacency_matrix, start_node, end_node)
num_nodes = size(adjacency_matrix, 1);
distances = inf(1, num_nodes);
visited = false(1, num_nodes);
previous = zeros(1, num_nodes);
distances(start_node) = 0;
while sum(visited) < num_nodes
current_node = find_min_distance(distances, visited);
visited(current_node) = true;
neighbors = find(adjacency_matrix(current_node, :));
for i = 1:length(neighbors)
neighbor = neighbors(i);
if ~visited(neighbor)
new_distance = distances(current_node) + adjacency_matrix(current_node, neighbor);
if new_distance < distances(neighbor)
distances(neighbor) = new_distance;
previous(neighbor) = current_node;
end
end
end
end
path = generate_path(previous, start_node, end_node);
end
function node = find_min_distance(distances, visited)
min_distance = inf;
node = -1;
for i = 1:length(distances)
if ~visited(i) && distances(i) < min_distance
min_distance = distances(i);
node = i;
end
end
end
function path = generate_path(previous, start_node, end_node)
if previous(end_node) == 0
path = [];
return;
end
path = [end_node];
current_node = end_node;
while current_node ~= start_node
current_node = previous(current_node);
path = [current_node, path];
end
end
```
这段代码使用邻接矩阵表示图的连接关系。输入参数`adjacency_matrix`是一个包含图连接关系的二维矩阵,`start_node`和`end_node`表示起点和终点节点的索引。函数返回最短路径的距离数组`distances`和路径数组`path`。
阅读全文