% function to find the connected componets of a graph.
% The graph should be given as an adjaceny matrix

% Output
% count = number of connected components
% sizes = list of sizes of components (number of vertices)

function [count,sizes,new_G]=find_comps(G)
% determine the number of vertices
V=size(G,1);
H=G+eye(V);
% this is a tricky way to find all the vertices
% that can be reached in V or fewer steps
for k=1:1+log2(V)
H=min(1,H+H^2);
end % for k
figure
spy(H)
done=zeros(1,V);
count=0;
list=[];
for k=1:V
if done(k)==0
% increment count of components
count=count+1;
% find all vertices reachable from k
adj=find(H(k,:)>0);
% find adjacency matrix of this component
M=G(adj,adj);
% display the adjacency matrix of non-trivial comps
if length(adj)>1
figure; hold on;
title(['find-comps, component # ',num2str(count),...
', size = ',num2str(length(adj))]);
spy(M);
end % if
% mark everything in component as found
% if adj is empty, we have a component with one vertex
done(adj)=1;
list=[list,adj];
sizes(count)=length(adj);
end % if
end % for k
new_G=G(list,list);
return