Finding All Cliques of an Undirected Graph

旧巷老猫 提交于 2019-12-25 18:24:25

问题


How can I list all cliques of an Undirected Graph ? (Not all maximal cliques, like the Bron-Kerbosch algorithm)


回答1:


The optimal solution is like this because in a complete graph there are 2^n cliques. Consider all subsets of nodes using a recursive function. And for each subset if all the edges are present between nodes of the subset, add 1 to your counter: (This is almost a pseudocode in C++)

int clique_counter = 0;
int n; //number of nodes in graph
//i imagine nodes are numbered from 1 to n

void f(int x, vector <int> &v){ //x is the current node
    if(x == n){
        bool is_clique = true;
        for(int i = 0; i < v.size(); i++){
            for(int j = i + 1; j < v.size(); j++){
                if(there is not an edge between node v[i] and v[j]) //it can't be clique
                    is_clique = false;
            }
        }
        if(is_clique == true){
            clique_counter++;
        }
        return;
    }

    //if x < n

    f(x + 1, v);

    v.push_back(x);
    f(x + 1, v);
    v.pop_back();
}


int main(){
    vector <int> v;
    f(1, v);
    cout << clique_counter << endl;

    return 0;
}


来源:https://stackoverflow.com/questions/37999282/finding-all-cliques-of-an-undirected-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!