Implementing Bron–Kerbosch algorithm in python

前端 未结 3 1561
旧巷少年郎
旧巷少年郎 2021-02-09 07:40

for a college project I\'m trying to implement the Bron–Kerbosch algorithm, that is, listing all maximal cliques in a given graph.

I\'m trying to implement the first alg

3条回答
  •  时光取名叫无心
    2021-02-09 08:03

    Implementation of two forms of the Bron-Kerbosch Algorithm from Wikipedia:

    Without pivoting

    algorithm BronKerbosch1(R, P, X) is
        if P and X are both empty then:
            report R as a maximal clique
        for each vertex v in P do
            BronKerbosch1(R ⋃ {v}, PN(v), XN(v))
            P := P \ {v}
            X := X ⋃ {v}
    
    adj_matrix = [
        [0, 1, 0, 0, 1, 0],
        [1, 0, 1, 0, 1, 0],
        [0, 1, 0, 1, 0, 0],
        [0, 0, 1, 0, 1, 1],
        [1, 1, 0, 1, 0, 0],
        [0, 0, 0, 1, 0, 0]]
    

    N = {
        i: set(num for num, j in enumerate(row) if j)
        for i, row in enumerate(adj_matrix)
    }
    
    print(N)
    # {0: {1, 4}, 1: {0, 2, 4}, 2: {1, 3}, 3: {2, 4, 5}, 4: {0, 1, 3}, 5: {3}}
    
    def BronKerbosch1(P, R=None, X=None):
        P = set(P)
        R = set() if R is None else R
        X = set() if X is None else X
        if not P and not X:
            yield R
        while P:
            v = P.pop()
            yield from BronKerbosch1(
                P=P.intersection(N[v]), R=R.union([v]), X=X.intersection(N[v]))
            X.add(v)
    
    P = N.keys()
    print(list(BronKerbosch1(P)))
    # [{0, 1, 4}, {1, 2}, {2, 3}, {3, 4}, {3, 5}]
    

    With pivoting

    algorithm BronKerbosch2(R, P, X) is
        if P and X are both empty then
            report R as a maximal clique
        choose a pivot vertex u in PX
        for each vertex v in P \ N(u):
            BronKerbosch2(R ⋃ {v}, P ⋂ N(v), X ⋂ N(v))
            P := P \ {v}
            X := X ⋃ {v}
    

    import random  
    
    def BronKerbosch2(P, R=None, X=None):
        P = set(P)
        R = set() if R is None else R
        X = set() if X is None else X
        if not P and not X:
            yield R
        try:
            u = random.choice(list(P.union(X)))
            S = P.difference(N[u])
        # if union of P and X is empty
        except IndexError:
            S = P
        for v in S:
            yield from BronKerbosch2(
                P=P.intersection(N[v]), R=R.union([v]), X=X.intersection(N[v]))
            P.remove(v)
            X.add(v)
    
    print(list(BronKerbosch2(P)))
    # [{0, 1, 4}, {1, 2}, {2, 3}, {3, 4}, {3, 5}]
    

提交回复
热议问题