prim算法代码matlab
时间: 2023-10-04 11:08:10 浏览: 64
Sure! Here's a MATLAB code implementation of the Prim's algorithm for finding the minimum spanning tree of a graph:
```matlab
function [MST] = prim_algorithm(adj_matrix)
num_vertices = size(adj_matrix, 1);
MST = zeros(num_vertices); % Initialize the minimum spanning tree
visited = zeros(1, num_vertices); % Keep track of visited vertices
visited(1) = 1; % Start from the first vertex
while sum(visited) < num_vertices
min_weight = Inf;
start_vertex = 0;
end_vertex = 0;
for i = 1:num_vertices
if visited(i)
row = adj_matrix(i, :);
for j = 1:num_vertices
if ~visited(j) && row(j) < min_weight
min_weight = row(j);
start_vertex = i;
end_vertex = j;
end
end
end
end
MST(start_vertex, end_vertex) = min_weight;
MST(end_vertex, start_vertex) = min_weight;
visited(end_vertex) = 1;
end
end
```
You can use this code by passing a weighted adjacency matrix to the `prim_algorithm` function. The function will return the minimum spanning tree (MST) in the form of an adjacency matrix.
Note: The input adjacency matrix should be a square matrix, where each element represents the weight of the edge between two vertices. If there is no edge between two vertices, the corresponding element should be set to `Inf` or any other large value.
Hope this helps! Let me know if you have any more questions.
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)