function fret = bfslevels(G,v)
% bfslevels : sizes of breadth-first search levels in undirected graph
%
% fringe = bfslevels(G)    BFS from random vtx of G and report level sizes
% fringe = bfslevels(G,v)  start from vtx v (1-based)
% bfslevels(...)           print results
%
% John Gilbert, 4 May 2011

% Make the graph undirected with no loops
G = G-diag(diag(G));
G = double(G|G');
nv = length(G);
ne = nnz(G)/2;
if nargin < 2
    v = 1+floor(nv*rand(1)); 
end;
if nargout==0
    fprintf('\nGraph has %d vertices and %d edges\n',nv,ne);
    fprintf(' Level   Size\n');
end;
b = zeros(nv,1);
b(v) = 1;
level = 1;
fringe = zeros(nv,1);
fringe(level) = 1;
while fringe(level) > 0
    if nargout==0
        fprintf('%4d %7d\n',level-1,fringe(level)); 
    end;
    level = level+1;
    bb = G*b | b;
    f = bb-b;
    b = bb;
    fringe(level) = nnz(f);
end;
level = level-1;
if nargout==0
    fprintf('Reached %d vertices in search\n', sum(fringe));
else
    fret = fringe(1:level);
end;
    