To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.
root / _FullBNT / BNT / graph / minspan.m @ 8:b5b38998ef3b
History | View | Annotate | Download (1.6 KB)
| 1 |
function [t,nk] = minspan(IJC) |
|---|---|
| 2 |
%MINSPAN Minimum weight spanning tree using Kruskal algorithm. |
| 3 |
%[t,nk] = minspan(IJC) |
| 4 |
% IJC = n x 3 matrix arc list [i j c] of arc heads, tails, and costs |
| 5 |
% t = n-element logical vector, where |
| 6 |
% t(i) = 1, if IJC(i,:) arc in spanning tree |
| 7 |
% t(i) = k, if IJC(i,:) arc in component k of forest |
| 8 |
% nk = number of components |
| 9 |
|
| 10 |
% Copyright (c) 1998-2001 by Michael G. Kay |
| 11 |
% Matlog Version 5 22-Aug-2001 |
| 12 |
|
| 13 |
% Input Error Checking ****************************************************** |
| 14 |
[n,cIJC] = size(IJC); |
| 15 |
if cIJC ~= 3 |
| 16 |
error('''IJC'' must be a 3-column matrix.')
|
| 17 |
elseif n < 1 |
| 18 |
error('''IJC'' must have at least one row.')
|
| 19 |
elseif any(IJC(:,1) < 1) | any(any(~isint(IJC(:,[1 2])))) |
| 20 |
error('Invalid arc index in IJC.')
|
| 21 |
end |
| 22 |
% End (Input Error Checking) ************************************************ |
| 23 |
|
| 24 |
i = IJC(:,1); j = abs(IJC(:,2)); |
| 25 |
m = max(max([i j])); |
| 26 |
|
| 27 |
sidxIJ = argsort(IJC(:,3)); |
| 28 |
i = i(sidxIJ); j = j(sidxIJ); |
| 29 |
|
| 30 |
t = logical(zeros(n,1)); |
| 31 |
k = 1; % Current arc |
| 32 |
nt = 0; % Number of arcs in spanning tree |
| 33 |
v = (1:m)'; % Arc labels |
| 34 |
|
| 35 |
while nt < m - 1 & k <= n |
| 36 |
if (v(i(k)) ~= v(j(k))) |
| 37 |
v(v==v(j(k))) = v(i(k)); |
| 38 |
t(k) = 1; |
| 39 |
nt = nt + 1; |
| 40 |
end |
| 41 |
k = k + 1; |
| 42 |
end |
| 43 |
|
| 44 |
idxIJ = invperm(sidxIJ); |
| 45 |
t = t(idxIJ); i = i(idxIJ); j = j(idxIJ); |
| 46 |
|
| 47 |
c = unique(v(unique([i; j]))); % Unique labels of arc vertices |
| 48 |
nk = length(c); |
| 49 |
if ~any(t), nk = 0; end % Self-loop not a component |
| 50 |
|
| 51 |
if nk > 1 |
| 52 |
for k = 1:nk |
| 53 |
t(t~=0 & v(i)==c(k)) = k; % Relabel to consecutive component numbers |
| 54 |
end |
| 55 |
end |
| 56 |
|