Implementing Bron–Kerbosch algorithm in python

前端 未结 3 1551
旧巷少年郎
旧巷少年郎 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:20

    As @VaughnCato correctly points out the error was iterating over P[:]. I thought it worth noting that you can "yield" this result, rather than printing, as follows (in this refactored code):

    def bronk2(R, P, X, g):
        if not any((P, X)):
            yield R
        for v in P[:]:
            R_v = R + [v]
            P_v = [v1 for v1 in P if v1 in N(v, g)]
            X_v = [v1 for v1 in X if v1 in N(v, g)]
            for r in bronk2(R_v, P_v, X_v, g):
                yield r
            P.remove(v)
            X.append(v)
    def N(v, g):
        return [i for i, n_v in enumerate(g[v]) if n_v]
    
    In [99]: list(bronk2([], range(6), [], graph))
    Out[99]: [[0, 1, 4], [1, 2], [2, 3], [3, 4], [3, 5]]
    

    In case someone is looking for a Bron–Kerbosch algorithm implementation in the future...

提交回复
热议问题