function ret = isconnected(EorA)
%ISCONNECTED Determines whether a graph is connected.
% ret = isconnected(E or A)
%     E = |E(G)|-by-2 matrix enumerating the edges of graph G
%     A = |V(G)|-by-|V(G)| binary adjacency matrix for graph G
%

% (by Delbert Dueck, delbert@cs.columbia.edu, 2009)

if size(EorA,2)==2, E=EorA; end;
if size(EorA,1)==size(EorA,2), A=EorA; end;

neighbors = cell(0);
if exist('E','var'), V=max(max(E));
    for v=1:V, neighbors{v,1}=unique([E(find(E(:,1)==v),2)',E(find(E(:,2)==v),1)']); end; % enumerate neighbors
elseif exist('A','var'), V=size(A,1);
    for v=1:V, neighbors{v,1}=find(A(v,:)); neighbors{v}(find(neighbors{v}==v))=[]; end; % enumerate neighbors
end;

visited = zeros(1,V);
isconnected_(1);
ret = all(visited);

    function isconnected_(v)
        % if all(visited), return; end; % not-necessary break-out condition
        
        for v_=neighbors{v},
            if ~visited(v_),
                visited(v_)=true;
                isconnected_(v_);
            end;
        end;
    end

end

% A = [0 1 0 0 0 0 0 0 1; ...
%      1 0 1 0 0 0 0 0 1; ...
%      0 1 0 1 0 0 0 1 1; ...
%      0 0 1 0 1 1 1 1 0; ...
%      0 0 0 1 0 1 0 0 0; ...
%      0 0 0 1 1 0 1 1 0; ...
%      0 0 0 1 0 1 0 1 0; ...
%      0 0 1 1 0 1 1 0 0; ...
%      1 1 1 0 0 0 0 0 0];
% for i=1:length(A), A(i,i)=1; end;
%      
% A = rand(20); A=.5*A+.5*A';
% A = (A>.5);
% for i=1:length(A), A(i,i)=1; end;
% maxcliques = findmaxcliques(A);

