Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

share|improve this question
    
Please give us an example and your desired output :) –  Öskå May 6 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 at 11:05
2  
See ConnectedComponents in the docs. Length@ConnectedComponents[g] gives the number of components in graph g. –  kguler May 6 at 11:07
    
Solved, thank you @kguler –  sdkbj May 6 at 11:17

2 Answers 2

up vote 1 down vote accepted

From the Documentation of ConnectedComponents

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

enter image description here

ConnectedComponents@g
{{1, 2, 3}, {4, 5}}

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

share|improve this answer

For example:

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

enter image description here

ConnectedGraphQ[testg]

yields False

Finding connected components:

ConnectedComponents[testg]

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.