@@ -140,3 +140,52 @@ def apply(self, graph, expression, evaluation, options):
140140 return Symbol ("System`False" )
141141 is_planar , _ = nx .check_planarity (graph .G )
142142 return Symbol ("System`True" ) if is_planar else Symbol ("System`False" )
143+
144+ class ConnectedComponents (_NetworkXBuiltin ):
145+ """
146+ >> g = Graph[{1 -> 2, 2 -> 3, 3 <-> 4}]; ConnectedComponents[g]
147+ = {{3, 4}, {2}, {1}}
148+
149+ >> g = Graph[{1 -> 2, 2 -> 3, 3 -> 1}]; ConnectedComponents[g]
150+ = {{1, 2, 3}}
151+
152+ >> g = Graph[{1 <-> 2, 2 <-> 3, 3 -> 4, 4 <-> 5}]; ConnectedComponents[g]
153+ = {{4, 5}, {1, 2, 3}}
154+ """
155+
156+ def apply (self , graph , expression , evaluation , options ):
157+ "ConnectedComponents[graph_, OptionsPattern[%(name)s]]"
158+ graph = self ._build_graph (graph , evaluation , options , expression )
159+ if graph :
160+ connect_fn = nx .strongly_connected_components if graph .G .is_directed () else nx .connected_components
161+ components = [
162+ Expression ("List" , * c ) for c in connect_fn (graph .G )
163+ ]
164+ return Expression ("List" , * components )
165+
166+
167+ class WeaklyConnectedComponents (_NetworkXBuiltin ):
168+ """
169+ >> g = Graph[{1 -> 2, 2 -> 3, 3 <-> 4}]; WeaklyConnectedComponents[g]
170+ = {{1, 2, 3, 4}}
171+
172+ >> g = Graph[{1 -> 2, 2 -> 3, 3 -> 1}]; WeaklyConnectedComponents[g]
173+ = {{1, 2, 3}}
174+
175+ >> g = Graph[{1 <-> 2, 2 <-> 3, 3 -> 4, 4 <-> 5, 6 <-> 7, 7 <-> 8}]; WeaklyConnectedComponents[g]
176+ = {{1, 2, 3, 4, 5}, {6, 7, 8}}
177+ """
178+
179+ def apply (self , graph , expression , evaluation , options ):
180+ "WeaklyConnectedComponents[graph_, OptionsPattern[%(name)s]]"
181+ graph = self ._build_graph (graph , evaluation , options , expression )
182+ if graph :
183+ components = nx .connected_components (graph .G .to_undirected ())
184+
185+ index = graph .vertices .get_index ()
186+ components = sorted (components , key = lambda c : index [next (iter (c ))])
187+
188+ vertices_sorted = graph .vertices .get_sorted ()
189+ result = [Expression ("List" , * vertices_sorted (c )) for c in components ]
190+
191+ return Expression ("List" , * result )
0 commit comments