码迷,mamicode.com
首页 > 其他好文 > 详细

prim algorithm

时间:2014-10-26 19:35:05      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   os   ar   for   sp   on   2014   

bubuko.com,布布扣

function re=biaoji(j,biao) %判断j点是否已被标记
l=length(biao);
for i=1:l
if j==biao(i)
re=1;
return;
end
end
re=0;
return;
end

clc;
clear all;
close all;

G=[0 4 0 0 0 0 0 8 0;
4 0 8 0 0 0 0 11 0;
0 8 0 7 0 4 0 0 2;
0 0 7 0 9 14 0 0 0;
0 0 0 9 0 10 0 0 0;
0 0 4 14 10 0 2 0 0;
0 0 0 0 0 2 0 1 6;
8 11 0 0 0 0 1 0 7;
0 0 2 0 0 0 6 7 0];
tmp = find(G~=0);
g = G(tmp);
k =length(G(:,1));
[tmpa,tmpb] = find(G~= 0);
e = [tmpa,tmpb];
E =[g,tmpa,tmpb];
[x,y] = cylinder(1,k);
plot(x(1,:),y(1,:),‘r*‘,‘markersize‘,10,‘linewidth‘,1);
axis([-1.5,1.5,-1.5,1.5]);
hold on
for i = 1 :k
tem = [‘V‘,int2str(i)];
text(x(1,i)+0.05,y(1,i),tem);
end
for i = 1:length(e(:,1))
plot(x(1,e(i,:)),y(1,e(i,:)),‘b‘,‘linewidth‘,1);
end
%% prim algorithm 
[m,n] = size(G);
q = [1];
k = 1;
A = [];
while length(q) ~= m
e = [];
for i = 1:k
for j = 1:n
if G(q(i),j)~= 0 && ~biaoji(j,q)
e = [e;G(q(i),j) q(i),j];
end
end
end
[junk index]=min(e(:,1)); %求与当前标记的所有元素相邻的权重最小的边的索引
A=[A;e(index,:)]; %最小生成树的三元组表示
q=[q e(index,3)];
k=k+1; 
end

a = A(:,2:3);
for i = 1:length(a(:,1))
plot(x(1,a(i,:)),y(1,a(i,:)),‘r-.‘,‘linewidth‘,2);
end

 

prim algorithm

标签:blog   http   io   os   ar   for   sp   on   2014   

原文地址:http://www.cnblogs.com/Kermit-Li/p/4052540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!