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
|