Skip to content

Instantly share code, notes, and snippets.

@jcchurch
Created June 16, 2011 14:53
Show Gist options
  • Save jcchurch/1029396 to your computer and use it in GitHub Desktop.
Save jcchurch/1029396 to your computer and use it in GitHub Desktop.
Quickly determine if a graph is connected
function result = connected(A)
% connected(A)
%
% This function takes an adjacency matrix A
% and returns if the graph is connected.
% 1 means connected.
% 0 means not connected.
% We assume that the starting result is connected.
% In lawyer terms, the graph is connected until proven
% not connected.
result = 1;
start = 1;
n = size(A, 1);
vertices = zeros(n, 1);
vertices(1) = 1;
queue = zeros(n, 1);
head = 1;
tail = 1;
queue(head) = 1;
% Begin Breadth-First Search Algorithm
while head <= tail
for i = 1:n
if queue(head) ~= i & A(queue(head), i) > 0 & A(queue(head), i) ~= Inf & vertices(i) == 0
tail = tail + 1;
queue(tail) = i;
vertices(i) = 1;
end
end
head = head + 1;
end
if tail ~= n
result = 0;
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment