请用matlab编写一个用于无向图的dijkstra算法,要求用户只用输入邻接矩阵和起点就可以输出一个点到所有点的最短路径
时间: 2024-02-11 16:09:54 浏览: 119
好的,以下是使用 MATLAB 编写的 Dijkstra 算法代码,可以用于无向图:
```matlab
function [distances, paths] = dijkstra(adjacencyMatrix, startNode)
numNodes = size(adjacencyMatrix, 1);
visited = false(1, numNodes);
distances = inf(1, numNodes);
distances(startNode) = 0;
paths = cell(1, numNodes);
for i = 1:numNodes
currentNode = findMinDistanceNode(visited, distances);
visited(currentNode) = true;
for j = 1:numNodes
if adjacencyMatrix(currentNode, j) > 0 && ~visited(j)
newDistance = distances(currentNode) + adjacencyMatrix(currentNode, j);
if newDistance < distances(j)
distances(j) = newDistance;
paths{j} = [paths{currentNode}, j];
end
end
end
end
end
function [minNode] = findMinDistanceNode(visited, distances)
minDistance = inf;
minNode = -1;
for i = 1:length(distances)
if ~visited(i) && distances(i) < minDistance
minDistance = distances(i);
minNode = i;
end
end
end
```
其中,`adjacencyMatrix` 是邻接矩阵,`startNode` 是起点。函数返回值 `distances` 是起点到每个点的最短距离数组,`paths` 是起点到每个点的最短路径数组。
阅读全文