function M = connected(x,y)
% find all the disconnected components of the pairs [xi,yi], return
% as a an array where each row is a list of elements

% example
%      x     y
%      1     2
%      3     4
%      3     5
%      4     5
%      6     7
%      6     8
%      7     8
%      6     9
%      7     9
%      8     9

% should return
% 1 2
% 3 4 5
% 6 7 8 9

% clear all;

%x=[1 3 3 4 6 6 7 6 7 8];
%y=[2 4 5 5 7 8 8 9 9 9];

M = zeros(length(unique(x)));
visited = zeros(max([x;,y]),1);
tmp = [];


N = length(x);
for i=1:N
  if( ~visited(x(i)) & ~visited(y(i)) )
    visited(x(i)) = 1;
    M(i,1) = x(i);
    ind = find(x==x(i));
    tmp = [tmp, y(ind)];
    visited(y(ind)) = 1;
    tmp = unique(tmp);		% has to be row vector
    M(i,2:length(tmp)+1) = tmp';
  end
  tmp = [];
end

M = unique(M,'rows');
% remove all-zero rows
M(find(sum(M') == 0),:) = [];
M(:,find(sum(M) == 0)) = [];
