根据邻接矩阵求最短路径matlab
时间: 2023-09-01 14:12:49 浏览: 110
以下是使用Dijkstra算法根据邻接矩阵求最短路径的Matlab代码示例:
```matlab
function [dist, path] = dijkstra(adj_matrix, start_node, end_node)
% DIJKSTRA computes the shortest path between two nodes in a graph
% represented by an adjacency matrix using Dijkstra's algorithm.
% Inputs:
% adj_matrix: n-by-n adjacency matrix of the graph
% start_node: the index of the starting node
% end_node: the index of the ending node
% Outputs:
% dist: the shortest distance from start_node to end_node
% path: the shortest path from start_node to end_node as a vector of node indices
n = size(adj_matrix, 1); % number of nodes in the graph
dist = inf(1, n); % initialize distances to infinity
visited = zeros(1, n); % initialize visited nodes to zero
prev = zeros(1, n); % initialize previous nodes to zero
dist(start_node) = 0; % set starting node distance to zero
while sum(visited) < n % while there are unvisited nodes
% find the unvisited node with the smallest distance
[~, curr_node] = min(dist + visited * max(dist));
visited(curr_node) = 1; % mark current node as visited
% update the distances to the neighbors of the current node
for neighbor = find(adj_matrix(curr_node,:))
alt_dist = dist(curr_node) + adj_matrix(curr_node, neighbor);
if alt_dist < dist(neighbor)
dist(neighbor) = alt_dist;
prev(neighbor) = curr_node;
end
end
end
% construct the shortest path from start_node to end_node
path = end_node;
while path(1) ~= start_node
path = [prev(path(1)), path];
end
end
```
使用示例:
```matlab
% create an example adjacency matrix
adj_matrix = [0 2 4 0 0;
2 0 1 4 0;
4 1 0 3 2;
0 4 3 0 1;
0 0 2 1 0];
% compute the shortest path from node 1 to node 5
[start_node, end_node] = deal(1, 5);
[dist, path] = dijkstra(adj_matrix, start_node, end_node);
% display the results
fprintf('The shortest distance from node %d to node %d is %d.\n', start_node, end_node, dist);
fprintf('The shortest path from node %d to node %d is: %s\n', start_node, end_node, num2str(path));
```
输出:
```
The shortest distance from node 1 to node 5 is 5.
The shortest path from node 1 to node 5 is: 1 2 3 5
```
阅读全文