Skip to content

Instantly share code, notes, and snippets.

@jcchurch
Created March 7, 2012 16:42
Show Gist options
  • Save jcchurch/1994278 to your computer and use it in GitHub Desktop.
Save jcchurch/1994278 to your computer and use it in GitHub Desktop.
Determine if a graph contains a cycle.
function yes = thereIsACycle(G)
% G is an n-by-n association matrix.
% An edge is defined by anything in that
% matrix that is not 0 and not positive infinity.
% Elements along the diagonal are ignored.
% Returns 1 if there is a cycle. 0 otherwise.
yes = 0;
n = size(G, 1);
seen = zeros(1, n);
queue = [1];
while length(queue) > 0
x = queue(1);
queue = queue(2:end);
if seen(x) == 0
seen(x) = 1;
for i = 1:n
if i~=x & G(x,i) ~= 0 & isinf(G(x,i)) == 0
queue = [queue i];
end
end
else
yes = 1;
break;
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment