To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Revision:

root / _FullBNT / BNT / graph / minimum_spanning_tree.m @ 8:b5b38998ef3b

History | View | Annotate | Download (1.61 KB)

1
function A = minimum_spanning_tree(C1, C2)
2
%
3
% Find the minimum spanning tree using Prim's algorithm.
4
% C1(i,j) is the primary cost of connecting i to j.
5
% C2(i,j) is the (optional) secondary cost of connecting i to j, used to break ties.
6
% We assume that absent edges have 0 cost.
7
% To find the maximum spanning tree, used -1*C.
8
% See Aho, Hopcroft & Ullman 1983, "Data structures and algorithms", p 237.
9

    
10
% Prim's is O(V^2). Kruskal's algorithm is O(E log E) and hence is more efficient
11
% for sparse graphs, but is implemented in terms of a priority queue.
12

    
13
% We partition the nodes into those in U and those not in U.
14
% closest(i) is the vertex in U that is closest to i in V-U.
15
% lowcost(i) is the cost of the edge (i, closest(i)), or infinity is i has been used.
16
% In Aho, they say C(i,j) should be "some appropriate large value" if the edge is missing.
17
% We set it to infinity.
18
% However, since lowcost is initialized from C, we must distinguish absent edges from used nodes.
19

    
20
n = length(C1);
21
if nargin==1, C2 = zeros(n); end
22
A = zeros(n);
23

    
24
closest = ones(1,n);
25
used = zeros(1,n); % contains the members of U
26
used(1) = 1; % start with node 1
27
C1(find(C1==0))=inf;
28
C2(find(C2==0))=inf;
29
lowcost1 = C1(1,:);
30
lowcost2 = C2(1,:);
31

    
32
for i=2:n
33
  ks = find(lowcost1==min(lowcost1));
34
  k = ks(argmin(lowcost2(ks)));
35
  A(k, closest(k)) = 1;
36
  A(closest(k), k) = 1;
37
  lowcost1(k) = inf;
38
  lowcost2(k) = inf;
39
  used(k) = 1;
40
  NU = find(used==0);
41
  for ji=1:length(NU)
42
    for j=NU(ji)
43
      if C1(k,j) < lowcost1(j)
44
	lowcost1(j) = C1(k,j);
45
	lowcost2(j) = C2(k,j);
46
	closest(j) = k;
47
      end
48
    end
49
  end
50
end
51