最短路径算法matlab代码
时间: 2023-11-08 10:55:30 浏览: 108
以下是一个使用Dijkstra算法求解最短路径的Matlab代码示例:
```matlab
function [distances, path = shortestPath(graph, startNode, endNode)
numNodes = size(graph, 1);
% 初始化距离数组和路径数组
distances = inf(1, numNodes);
distances(startNode) = 0;
visited = false(1, numNodes);
path = zeros(1, numNodes);
% 运行Dijkstra算法
for i = 1:numNodes
% 选择当前距离最小且未访问过的节点
[~, currentNode = min(distances .* ~visited);
visited(currentNode) = true;
% 更新与当前节点相邻节点的距离
neighbors = find(graph(currentNode, :));
for j = 1:length(neighbors)
neighbor = neighbors(j);
if ~visited(neighbor) && distances(currentNode) + graph(currentNode, neighbor) < distances(neighbor)
distances(neighbor) = distances(currentNode) + graph(currentNode, neighbor);
path(neighbor) = currentNode;
end
end
end
% 构建最短路径
currentNode = endNode;
pathLength = 1;
while currentNode ~= startNode
currentNode = path(currentNode);
pathLength = pathLength + 1;
end
path = zeros(1, pathLength);
currentNode = endNode;
for i = pathLength:-1:1
path(i) = currentNode;
currentNode = path(currentNode);
end
end
```
这个代码实现了Dijkstra算法,使用了邻接矩阵表示图。输入参数为图的邻接矩阵 `graph`、起始节点 `startNode` 和目标节点 `endNode`。函数返回最短路径距离数组 `distances` 和路径数组 `path`。
希望这个代码对你有帮助!如果有任何问题,请随时提问。
阅读全文