我正在尝试解决集团问题。我正在使用 Bron Kerbosch Clique 算法,它很好地用 java 编写,一个聪明的实现可以在这里找到。然而,由于派系的硬度,它可能非常缓慢,
我想要做的是使用一组我知道它们是连接的初始顶点。然后调用方法。对于我的一生,我不确定我在这里做错了什么,结果不是派系。
注意:注释代码来自原始代码(上面链接)。
public class BronKerboschCliqueFinder<V, E> {
//~ Instance fields --------------------------------------------------------
private final UndirectedGraph<V, E> graph;
private Collection<Set<V>> cliques;
// public Collection<Set<V>> getAllMaximalCliques()
public Collection<Set<V>> getAllMaximalCliqes(Set<String> initials){
{
// TODO: assert that graph is simple
cliques = new ArrayList<Set<V>>();
List<V> potential_clique = new ArrayList<V>();
List<V> candidates = new ArrayList<V>();
List<V> already_found = new ArrayList<V>();
// candidates.addAll(graph.getVertices()); instead I do this:
for(V v : graph.getVertices()){
if(initial.contains(v)){
potential_clique.add(v);
}else{
candidates.add(v);
}
}
findCliques(potential_clique, candidates, already_found);
return cliques;
}
private void findCliques(
List<V> potential_clique,
List<V> candidates,
List<V> already_found)
{
List<V> candidates_array = new ArrayList<V>(candidates);
if (!end(candidates, already_found)) {
// for each candidate_node in candidates do
for (V candidate : candidates_array) {
List<V> new_candidates = new ArrayList<V>();
List<V> new_already_found = new ArrayList<V>();
// move candidate node to potential_clique
potential_clique.add(candidate);
candidates.remove(candidate);
// create new_candidates by removing nodes in candidates not
// connected to candidate node
for (V new_candidate : candidates) {
if (graph.isNeighbor(candidate, new_candidate))
{
new_candidates.add(new_candidate);
} // of if
} // of for
// create new_already_found by removing nodes in already_found
// not connected to candidate node
for (V new_found : already_found) {
if (graph.isNeighbor(candidate, new_found)) {
new_already_found.add(new_found);
} // of if
} // of for
// if new_candidates and new_already_found are empty
if (new_candidates.isEmpty() && new_already_found.isEmpty()) {
// potential_clique is maximal_clique
cliques.add(new HashSet<V>(potential_clique));
return;
} // of if
else {
// recursive call
findCliques(
potential_clique,
new_candidates,
new_already_found);
} // of else
// move candidate_node from potential_clique to already_found;
already_found.add(candidate);
potential_clique.remove(candidate);
} // of for
} // of if
}
private boolean end(List<V> candidates, List<V> already_found)
{
// if a node in already_found is connected to all nodes in candidates
boolean end = false;
int edgecounter;
for (V found : already_found) {
edgecounter = 0;
for (V candidate : candidates) {
if (graph.isNeighbor(found, candidate)) {
edgecounter++;
} // of if
} // of for
if (edgecounter == candidates.size()) {
end = true;
}
} // of for
return end;
}
}
所以简而言之,我唯一的改变是在getAllMaximalCliques
方法上。我不太确定递归调用方法在这里是如何工作的。
如果可以提供任何帮助或指导,我将不胜感激。