文末附代码
%Judge whether an undirected graph has cycle
function Re = unhascycle(G)
e=numedges(G);
n=numnodes(G);
bins=conncomp(G);
c=bins(end);
if e>n-c
Re=1;
else
Re=0;
end
end
%Solving minimum spanning tree by Kruskal algorithm
function [weight,tree] = Kruskal(G) adj=full(adjacency(G,'Weighted')); order=length(adj);
Q=sortrows(G.Edges,2)
tree=graph;
while numedges(tree)~=order-1
edge=Q(1,:);
Q(1,:)=[];
tree=addedge(tree,edge);
while unhascycle(tree)
tree=rmedge(tree,edge.EndNodes(1),edge.EndNodes(2));
edge=Q(1,:);
Q(1,:)=[];
tree=addedge(tree,edge);
end
end
weight=sum(tree.Edges.Weight);
h=plot(G,'EdgeLabel',G.Edges.Weight);
highlight(h,tree,'EdgeColor','r','LineWidth',2);
end
%Solving minimum spanning tree by Prim algorithm
function [weight,tree] = Prim(G)
adj=full(adjacency(G,'Weighted'));
order=length(adj);
Q=sortrows(G.Edges,2);
tree=graph;
edge=Q(1,:);
Q(1,:)=[];
tree=addedge(tree,edge);
while numedges(tree)~=order-1
r=1;
while(length(intersect(tree.Edges.EndNodes,Q.EndNodes(r,:)))~=1)
r=r+1;
end
edge=Q(r,:);
Q(r,:)=[];
tree=addedge(tree,edge);
end
weight=sum(tree.Edges.Weight);
h=plot(G,'EdgeLabel',G.Edges.Weight);
highlight(h,tree,'EdgeColor','r','LineWidth',2);
end
%Solving minimum spanning tree by 0-1 integer programming
function [weight,edge] = MST(G)
adj=full(adjacency(G,'Weighted'));
order=length(adj);
adj(adj==0)=10000;adj(1:order+1:end)=0;
prob=optimproblem;
x=optimvar('x',order,order,'Type','integer','LowerBound',0,'UpperBound',1);
u=optimvar('u',order,'LowerBound',0);
prob.Objective=sum(sum(adj.*x));
prob.Constraints.con1=[sum(x(1,:))>=1;u(2,end)>=1];
prob.Constraints.con2=u(2:end)<=order-1;
prob.Constraints.con3=[sum(x(:,[2:end]))'==1;u(1)==0];
con4=[];
for i=1:order
for j=2:order
con4=[con4,u(i)-u(j)+order*x(i,j)<=order-1];
end
end
prob.Constraints.con4=con4;
[sol,fval]=solve(prob);
[i,j]=find(sol.x);
weight=fval;
edge=[i,j];
end