annotate toolboxes/FullBNT-1.0.7/graph/topological_sort.m @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
rev   line source
Daniel@0 1 function order = topological_sort(A)
Daniel@0 2 % TOPOLOGICAL_SORT Return the nodes in topological order (parents before children).
Daniel@0 3 % order = topological_sort(adj_mat)
Daniel@0 4
Daniel@0 5 n = length(A);
Daniel@0 6 indeg = zeros(1,n);
Daniel@0 7 zero_indeg = []; % a stack of nodes with no parents
Daniel@0 8 for i=1:n
Daniel@0 9 indeg(i) = length(parents(A,i));
Daniel@0 10 if indeg(i)==0
Daniel@0 11 zero_indeg = [i zero_indeg];
Daniel@0 12 end
Daniel@0 13 end
Daniel@0 14
Daniel@0 15 t=1;
Daniel@0 16 order = zeros(1,n);
Daniel@0 17 while ~isempty(zero_indeg)
Daniel@0 18 v = zero_indeg(1); % pop v
Daniel@0 19 zero_indeg = zero_indeg(2:end);
Daniel@0 20 order(t) = v;
Daniel@0 21 t = t + 1;
Daniel@0 22 cs = children(A, v);
Daniel@0 23 for j=1:length(cs)
Daniel@0 24 c = cs(j);
Daniel@0 25 indeg(c) = indeg(c) - 1;
Daniel@0 26 if indeg(c) == 0
Daniel@0 27 zero_indeg = [c zero_indeg]; % push c
Daniel@0 28 end
Daniel@0 29 end
Daniel@0 30 end