1 25 41 package org.jgrapht.alg; 42 43 import java.util.*; 44 45 import org.jgrapht.*; 46 47 48 56 public class BronKerboschCliqueFinder<V, E> 57 { 58 59 61 private final Graph<V, E> graph; 62 63 private Collection<Set<V>> cliques; 64 65 67 73 public BronKerboschCliqueFinder(Graph<V, E> graph) 74 { 75 this.graph = graph; 76 } 77 78 80 88 public Collection<Set<V>> getAllMaximalCliques() 89 { 90 92 cliques = new ArrayList<Set<V>>(); 93 List<V> potential_clique = new ArrayList<V>(); 94 List<V> candidates = new ArrayList<V>(); 95 List<V> already_found = new ArrayList<V>(); 96 candidates.addAll(graph.vertexSet()); 97 findCliques(potential_clique, candidates, already_found); 98 return cliques; 99 } 100 101 107 public Collection<Set<V>> getBiggestMaximalCliques() 108 { 109 getAllMaximalCliques(); 111 112 int maximum = 0; 113 Collection<Set<V>> biggest_cliques = new ArrayList<Set<V>>(); 114 for (Set<V> clique : cliques) { 115 if (maximum < clique.size()) { 116 maximum = clique.size(); 117 } 118 } 119 for (Set<V> clique : cliques) { 120 if (maximum == clique.size()) { 121 biggest_cliques.add(clique); 122 } 123 } 124 return biggest_cliques; 125 } 126 127 private void findCliques( 128 List<V> potential_clique, 129 List<V> candidates, 130 List<V> already_found) 131 { 132 List<V> candidates_array = new ArrayList<V>(candidates); 133 if (!end(candidates, already_found)) { 134 for (V candidate : candidates_array) { 136 List<V> new_candidates = new ArrayList<V>(); 137 List<V> new_already_found = new ArrayList<V>(); 138 139 potential_clique.add(candidate); 141 candidates.remove(candidate); 142 143 for (V new_candidate : candidates) { 146 if (graph.containsEdge(candidate, new_candidate)) { 147 new_candidates.add(new_candidate); 148 } } 151 for (V new_found : already_found) { 154 if (graph.containsEdge(candidate, new_found)) { 155 new_already_found.add(new_found); 156 } } 159 if (new_candidates.isEmpty() && new_already_found.isEmpty()) { 161 cliques.add(new HashSet<V>(potential_clique)); 163 } else { 165 findCliques( 167 potential_clique, 168 new_candidates, 169 new_already_found); 170 } 172 already_found.add(candidate); 174 potential_clique.remove(candidate); 175 } } } 178 179 private boolean end(List<V> candidates, List<V> already_found) 180 { 181 boolean end = false; 183 int edgecounter; 184 for (V found : already_found) { 185 edgecounter = 0; 186 for (V candidate : candidates) { 187 if (graph.containsEdge(found, candidate)) { 188 edgecounter++; 189 } } if (edgecounter == candidates.size()) { 192 end = true; 193 } 194 } return end; 196 } 197 } 198 | Popular Tags |