Вы можете найти все подключенные компоненты, используя функцию connected_componets()
.Впоследствии вы можете отфильтровать компоненты, которые состоят из трех узлов:
import networkx as nx
import pandas as pd
from itertools import chain
adj_matrix = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
df = pd.DataFrame(adj_matrix)
G = nx.from_pandas_adjacency(df)
# filter components of size 3
triplets = [c for c in nx.connected_components(G) if len(c) == 3]
triples_chain = set(chain.from_iterable(triplets))
color = ['lime' if n in triples_chain else 'pink' for n in G.nodes()]
# jupyter notebook
%matplotlib inline
nx.draw(G, with_labels=True, node_color=color, node_size=1000)