dijsktra算法代码matlab
时间: 2023-09-02 07:05:32 浏览: 110
以下是使用Matlab实现Dijkstra算法的示例代码:
```matlab
function [distances, previous = dijkstra(adjacencyMatrix, source)
numNodes = size(adjacencyMatrix, 1);
distances = inf(1, numNodes);
previous = zeros(1, numNodes);
visited = false(1, numNodes);
distances(source) = 0;
for i = 1:numNodes
currentNode = getNextNode(distances, visited);
visited(currentNode) = true;
neighbors = find(adjacencyMatrix(currentNode, :));
for j = 1:length(neighbors)
neighbor = neighbors(j);
if ~visited(neighbor)
distance = distances(currentNode) + adjacencyMatrix(currentNode, neighbor);
if distance < distances(neighbor)
distances(neighbor) = distance;
previous(neighbor) = currentNode;
end
end
end
end
end
function nextNode = getNextNode(distances, visited)
minDistance = inf;
nextNode = -1;
for i = 1:length(distances)
if ~visited(i) && distances(i) <= minDistance
minDistance = distances(i);
nextNode = i;
end
end
end
```
使用示例:
```matlab
% 定义邻接矩阵
adjacencyMatrix = [
0 7 0 9 0 14;
7 0 10 15 0 0;
0 10 0 11 0 2;
9 15 11 0 6 0;
0 0 0 6 0 9;
14 0 2 0 9 0
];
sourceNode = 1; % 源节点
= dijkstra(adjacencyMatrix, sourceNode);
% 打印最短路径和距离
for i = 1:length(distances)
if i ~= sourceNode
path = getPath(previous, i);
fprintf('从节点 %d 到节点 %d 的最短路径: %s,距离: %d\n', sourceNode, i, path, distances(i));
end
end
function path = getPath(previous, node)
path = "";
while node ~= 0
path = strcat(string(node), "->", path);
node = previous(node);
end
end
```
这段代码演示了如何使用Dijkstra算法找到从源节点到其他节点的最短路径及距离。首先,我们定义一个邻接矩阵来表示图的连接关系。然后,我们指定源节点,并调用`dijkstra`函数计算最短路径和距离。最后,我们通过遍历结果来打印出源节点到其他节点的最短路径和距离。
请注意,这只是一个简单的示例代码,适用于小规模的图。在实际应用中,可能需要对算法进行修改以处理更大规模的图或其他特殊情况。
阅读全文