function cycles = allcycsn(a)
% All cycles in graph of matrix A
%
% function cycles = allcycsn(a)
%
% a square (boolean) successor matrix (n,n)
% cycles matrix (?,n), each row contains the node numbers in a walk around
% a cycle; the matrix is padded with 0's on the right
%
% The algorithm is an exhaustive traversal of the digraph with pruning. An
% early version is in APL in Evans & Larsen (1981). To get the cyc-
% les as boolean lists, use 'allcycs'.
[n,dum] = size(a) ;
paths = (1:n)' ;
cycles = [] ;
%%%%%%%%%%%%%%%%%%%%%%%%%
emptycyc = zeros(1,(n+1)) ;
%%%%%%%%%%%%%%%%%%%%%%%%%
while ~isempty(paths),
[maxp,dist] = size(paths) ;
newpaths = [] ;
for i=1:maxp,
curpath = paths(i,:) ;
%%%%%%%%%%%%%
candids = find(a(:,curpath(dist))) ;
%%%%%%%%%%%%%
for j = 1:length(candids),
cand = candids(j) ;
%%%%%%%%%%%%%%%%%%%%%%%%%
p1 = all(cand ~= curpath) ;
%%%%%%%%%%%%%%%%%%%%%%%%%
p2 = cand == curpath(1) ;
p3 = cand > curpath(1) ;
if p2,
newcyc = emptycyc ;
%%%%%%%%%%%%%%%%%%%%%%%%%
newcyc(1:(length(curpath)+1)) = [curpath,cand] ;
cycles = [cycles;newcyc];
%%%%%%%%%%%%%%%%%%%%%%%%%
elseif p1 & p3,
newpath = [curpath,cand] ;
newpaths = [newpaths;newpath] ;
end ;
end ;
end ;
paths = newpaths ;
end ;