TITLE: Easiest way to determine all disconnected sets from a graph?
QUESTION [5 upvotes]: Suppose that I have a un-directed graph of nodes and edges, I would like to know all sets of nodes that do not connect with any other nodes in the graph.
Here is a concrete example to help you picture what I'm asking. In the following graph, all x nodes are connected to their adjacent (diagonal included) x nodes and the same goes for o nodes and b nodes.
x o o
b x o
b b x  
I wrote an algorithm that does this by taking a node and using depth first search to find all nodes connected to it. Then I remove those nodes from the graph and repeat with a new node until there are no more nodes left in the graph.
I'm starting to think that this isn't the most efficient method and that there has to be a way to do this using an adjacency matrix or something similar. If I were to translate the above graph into an adjacency matrix and name each node (1..9, left to right, top to bottom), it would look like this:
~~ 1 2 3 4 5 6 7 8 9
1 | 0 0 0 0 1 0 0 0 0
2 | 0 0 1 0 0 1 0 0 0
3 | 0 1 0 0 0 1 0 0 0
4 | 0 0 0 0 0 0 1 1 0
5 | 1 0 0 0 0 0 0 0 1
6 | 0 1 1 0 0 0 0 0 0
7 | 0 0 0 1 0 0 0 1 0
8 | 0 0 0 1 0 0 1 0 0
9 | 0 0 0 0 1 0 0 0 0  
I put zeros down the diagonal, but I'm not sure if that's right notation for an adjacency matrix. Also, since it's an undirected graph, I know that the matrix is symmetrical down the diagonal. Beyond that, I'm stuck. I just have a feeling that something about this matrix will make it easier to identify the 3 distinct unconnected groups beyond what I've done already. Does anyone have an idea for an algorithm that will help me?
Thanks in advance.

REPLY [4 votes]: Here is a fancy way of doing it. Construct the Laplacian matrix $L = D - A$ and find the eigenvalues and eigenvector of $L.$ The eigenvalues are $\lambda = \{0,0,0,1,3,3,3,3,3\}$ in your case and the first three zeros tell me that there are 3 disconnected sets. The associated eigenvectors are
$$
\begin{eqnarray}
 \mathbf{x}_1 &=& \left[\frac{-1}{\sqrt{3}}, 0,0,0, \frac{-1}{\sqrt{3}}, 0,0,0, \frac{-1}{\sqrt{3}}\right]^T,\\
\mathbf{x}_2 &=& \left[0,0,0,\frac{1}{\sqrt{3}},0,0,\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}},0\right]^T,\\
\mathbf{x}_3 &=& \left[0,\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}},0,0,\frac{1}{\sqrt{3}},0,0,0\right]^T.
\end{eqnarray}
$$
From indices of the nonzero entries I see the clusters are $C_1 = \{v_1, v_5, v_9\},$
$C_2 = \{v_4, v_7, v_8\},$ and $C_3 = \{v_2, v_3, v_6\}.$