Finding k-Sized Clique Subsets in NetworkX Graphs

  • Share this:

Code introduction


This function is used to find all cliques of size k in the given NetworkX graph. A clique is a subset of vertices of an undirected graph such that every two distinct vertices are adjacent.


Technology Stack : NetworkX, itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def find_cliques(graph, k):
    """
    Find all cliques of size k in the given graph.

    :param graph: NetworkX graph
    :param k: Size of the cliques
    :return: List of cliques
    """
    import networkx as nx
    from itertools import combinations

    if not isinstance(graph, nx.Graph):
        raise ValueError("Input graph must be a NetworkX graph")

    if not isinstance(k, int) or k <= 0:
        raise ValueError("Clique size must be a positive integer")

    cliques = []
    for nodes in combinations(graph.nodes(), k):
        subgraph = graph.subgraph(nodes)
        if nx.is_connected(subgraph):
            cliques.append(nodes)

    return cliques