How to find number of connected components of graph G?

Is there a command that can count the number of components of a graph, in the same way that VertexCount[G] counts vertices?

-
Please give us an example and your desired output :) – Öskå May 6 '14 at 11:04
I want the number of connected components. For the graph in the picture here: wikipedia.org/wiki/Connected_component_(graph_theory) I would want the number 3 as output. – sdkbj May 6 '14 at 11:05
See ConnectedComponents in the docs. Length@ConnectedComponents[g] gives the number of components in graph g. – kglr May 6 '14 at 11:07
Solved, thank you @kguler – sdkbj May 6 '14 at 11:17

From the Documentation of ConnectedComponents

g = Graph[{1 <-> 2, 2 <-> 3, 3 <-> 1, 4 <-> 5}, VertexLabels -> "Name", ImagePadding -> 5]


ConnectedComponents@g

{{1, 2, 3}, {4, 5}}


So Length@ConnectedComponents@g gives you the number of connected components.

-

For example:

testg = Graph[{1 \[UndirectedEdge] 2, 3 \[UndirectedEdge] 4,
4 \[UndirectedEdge] 5, 3 \[UndirectedEdge] 5}]


ConnectedGraphQ[testg]


yields False

Finding connected components:

ConnectedComponents[testg]


yields:{{4, 3, 5}, {2, 1}}

-