Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cliques.h
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14//
15// Maximal clique algorithms, based on the Bron-Kerbosch algorithm.
16// See http://en.wikipedia.org/wiki/Bron-Kerbosch_algorithm
17// and
18// C. Bron and J. Kerbosch, Joep, "Algorithm 457: finding all cliques of an
19// undirected graph", CACM 16 (9): 575-577, 1973.
20// http://dl.acm.org/citation.cfm?id=362367&bnc=1.
21//
22// Keywords: undirected graph, clique, clique cover, Bron, Kerbosch.
23
24#ifndef OR_TOOLS_GRAPH_CLIQUES_H_
25#define OR_TOOLS_GRAPH_CLIQUES_H_
26
27#include <cstddef>
28#include <cstdint>
29#include <functional>
30#include <limits>
31#include <numeric>
32#include <string>
33#include <utility>
34#include <vector>
35
36#include "absl/strings/str_cat.h"
40#include "ortools/util/bitset.h"
42
43namespace operations_research {
44
45// Finds all maximal cliques, even of size 1, in the
46// graph described by the graph callback. graph->Run(i, j) indicates
47// if there is an arc between i and j.
48// This function takes ownership of 'callback' and deletes it after it has run.
49// If 'callback' returns true, then the search for cliques stops.
50void FindCliques(std::function<bool(int, int)> graph, int node_count,
51 std::function<bool(const std::vector<int>&)> callback);
52
53// Covers the maximum number of arcs of the graph with cliques. The graph
54// is described by the graph callback. graph->Run(i, j) indicates if
55// there is an arc between i and j.
56// This function takes ownership of 'callback' and deletes it after it has run.
57// It calls 'callback' upon each clique.
58// It ignores cliques of size 1.
59void CoverArcsByCliques(std::function<bool(int, int)> graph, int node_count,
60 std::function<bool(const std::vector<int>&)> callback);
61
62// Possible return values of the callback for reporting cliques. The returned
63// value determines whether the algorithm will continue the search.
64enum class CliqueResponse {
65 // The algorithm will continue searching for other maximal cliques.
67 // The algorithm will stop the search immediately. The search can be resumed
68 // by calling BronKerboschAlgorithm::Run (resp. RunIterations) again.
70};
71
72// The status value returned by BronKerboschAlgorithm::Run and
73// BronKerboschAlgorithm::RunIterations.
75 // The algorithm has enumerated all maximal cliques.
77 // The search algorithm was interrupted either because it reached the
78 // iteration limit or because the clique callback returned
79 // CliqueResponse::STOP.
81};
82
83// Implements the Bron-Kerbosch algorithm for finding maximal cliques.
84// The graph is represented as a callback that gets two nodes as its arguments
85// and it returns true if and only if there is an arc between the two nodes. The
86// cliques are reported back to the user using a second callback.
87//
88// Typical usage:
89// auto graph = [](int node1, int node2) { return true; };
90// auto on_clique = [](const std::vector<int>& clique) {
91// LOG(INFO) << "Clique!";
92// };
93//
94// BronKerboschAlgorithm<int> bron_kerbosch(graph, num_nodes, on_clique);
95// bron_kerbosch.Run();
96//
97// or:
98//
99// BronKerboschAlgorithm bron_kerbosch(graph, num_nodes, clique);
100// bron_kerbosch.RunIterations(kMaxNumIterations);
101//
102// This is a non-recursive implementation of the Bron-Kerbosch algorithm with
103// pivots as described in the paper by Bron and Kerbosch (1973) (the version 2
104// algorithm in the paper).
105// The basic idea of the algorithm is to incrementally build the cliques using
106// depth-first search. During the search, the algorithm maintains two sets of
107// candidates (nodes that are connected to all nodes in the current clique):
108// - the "not" set - these are candidates that were already visited by the
109// search and all the maximal cliques that contain them as a part of the
110// current clique were already reported.
111// - the actual candidates - these are candidates that were not visited yet, and
112// they can be added to the clique.
113// In each iteration, the algorithm does the first of the following actions that
114// applies:
115// A. If there are no actual candidates and there are candidates in the "not"
116// set, or if all actual candidates are connected to the same node in the
117// "not" set, the current clique can't be extended to a maximal clique that
118// was not already reported. Return from the recursive call and move the
119// selected candidate to the set "not".
120// B. If there are no candidates at all, it means that the current clique can't
121// be extended and that it is in fact a maximal clique. Report it to the user
122// and return from the recursive call. Move the selected candidate to the set
123// "not".
124// C. Otherwise, there are actual candidates, extend the current clique with one
125// of these candidates and process it recursively.
126//
127// To avoid unnecessary steps, the algorithm selects a pivot at each level of
128// the recursion to guide the selection of candidates added to the current
129// clique. The pivot can be either in the "not" set and among the actual
130// candidates. The algorithm tries to move the pivot and all actual candidates
131// connected to it to the set "not" as quickly as possible. This will fulfill
132// the conditions of step A, and the search algorithm will be able to leave the
133// current branch. Selecting a pivot that has the lowest number of disconnected
134// nodes among the candidates can reduce the running time significantly.
135//
136// The worst-case maximal depth of the recursion is equal to the number of nodes
137// in the graph, which makes the natural recursive implementation impractical
138// for nodes with more than a few thousands of nodes. To avoid the limitation,
139// this class simulates the recursion by maintaining a stack with the state at
140// each level of the recursion. The algorithm then runs in a loop. In each
141// iteration, the algorithm can do one or both of:
142// 1. Return to the previous recursion level (step A or B of the algorithm) by
143// removing the top state from the stack.
144// 2. Select the next candidate and enter the next recursion level (step C of
145// the algorithm) by adding a new state to the stack.
146//
147// The worst-case time complexity of the algorithm is O(3^(N/3)), and the memory
148// complexity is O(N^2), where N is the number of nodes in the graph.
149template <typename NodeIndex>
151 public:
152 // A callback called by the algorithm to test if there is an arc between a
153 // pair of nodes. The callback must return true if and only if there is an
154 // arc. Note that to function properly, the function must be symmetrical
155 // (represent an undirected graph).
156 using IsArcCallback = std::function<bool(NodeIndex, NodeIndex)>;
157 // A callback called by the algorithm to report a maximal clique to the user.
158 // The clique is returned as a list of nodes in the clique, in no particular
159 // order. The caller must make a copy of the vector if they want to keep the
160 // nodes.
161 //
162 // The return value of the callback controls how the algorithm continues after
163 // this clique. See the description of the values of 'CliqueResponse' for more
164 // details.
166 std::function<CliqueResponse(const std::vector<NodeIndex>&)>;
167
168 // Initializes the Bron-Kerbosch algorithm for the given graph and clique
169 // callback function.
171 CliqueCallback clique_callback)
172 : is_arc_(std::move(is_arc)),
173 clique_callback_(std::move(clique_callback)),
174 num_nodes_(num_nodes) {}
175
176 // Runs the Bron-Kerbosch algorithm for kint64max iterations. In practice,
177 // this is equivalent to running until completion or until the clique callback
178 // returns BronKerboschAlgorithmStatus::STOP. If the method returned because
179 // the search is finished, it will return COMPLETED; otherwise, it will return
180 // INTERRUPTED and it can be resumed by calling this method again.
182
183 // Runs at most 'max_num_iterations' iterations of the Bron-Kerbosch
184 // algorithm. When this function returns INTERRUPTED, there is still work to
185 // be done to process all the cliques in the graph. In such case the method
186 // can be called again and it will resume the work where the previous call had
187 // stopped. When it returns COMPLETED any subsequent call to the method will
188 // resume the search from the beginning.
189 BronKerboschAlgorithmStatus RunIterations(int64_t max_num_iterations);
190
191 // Runs at most 'max_num_iterations' iterations of the Bron-Kerbosch
192 // algorithm, until the time limit is exceeded or until all cliques are
193 // enumerated. When this function returns INTERRUPTED, there is still work to
194 // be done to process all the cliques in the graph. In such case the method
195 // can be called again and it will resume the work where the previous call had
196 // stopped. When it returns COMPLETED any subsequent call to the method will
197 // resume the search from the beginning.
198 BronKerboschAlgorithmStatus RunWithTimeLimit(int64_t max_num_iterations,
200
201 // Runs the Bron-Kerbosch algorithm for at most kint64max iterations, until
202 // the time limit is excceded or until all cliques are enumerated. In
203 // practice, running the algorithm for kint64max iterations is equivalent to
204 // running until completion or until the other stopping conditions apply. When
205 // this function returns INTERRUPTED, there is still work to be done to
206 // process all the cliques in the graph. In such case the method can be called
207 // again and it will resume the work where the previous call had stopped. When
208 // it returns COMPLETED any subsequent call to the method will resume the
209 // search from the beginning.
211 return RunWithTimeLimit(std::numeric_limits<int64_t>::max(), time_limit);
212 }
213
214 private:
215 DEFINE_INT_TYPE(CandidateIndex, ptrdiff_t);
216
217 // A data structure that maintains the variables of one "iteration" of the
218 // search algorithm. These are the variables that would normally be allocated
219 // on the stack in the recursive implementation.
220 //
221 // Note that most of the variables in the structure are explicitly left
222 // uninitialized by the constructor to avoid wasting resources on values that
223 // will be overwritten anyway. Most of the initialization is done in
224 // BronKerboschAlgorithm::InitializeState.
225 struct State {
226 State() {}
227 State(const State& other)
228 : pivot(other.pivot),
229 num_remaining_candidates(other.num_remaining_candidates),
230 candidates(other.candidates),
231 first_candidate_index(other.first_candidate_index),
232 candidate_for_recursion(other.candidate_for_recursion) {}
233
234 State& operator=(const State& other) {
235 pivot = other.pivot;
236 num_remaining_candidates = other.num_remaining_candidates;
237 candidates = other.candidates;
238 first_candidate_index = other.first_candidate_index;
239 candidate_for_recursion = other.candidate_for_recursion;
240 return *this;
241 }
242
243 // Moves the first candidate in the state to the "not" set. Assumes that the
244 // first candidate is also the pivot or a candidate disconnected from the
245 // pivot (as done by RunIteration).
246 inline void MoveFirstCandidateToNotSet() {
247 ++first_candidate_index;
248 --num_remaining_candidates;
249 }
250
251 // Creates a human-readable representation of the current state.
252 std::string DebugString() {
253 std::string buffer;
254 absl::StrAppend(&buffer, "pivot = ", pivot,
255 "\nnum_remaining_candidates = ", num_remaining_candidates,
256 "\ncandidates = [");
257 for (CandidateIndex i(0); i < candidates.size(); ++i) {
258 if (i > 0) buffer += ", ";
259 absl::StrAppend(&buffer, candidates[i]);
260 }
261 absl::StrAppend(
262 &buffer, "]\nfirst_candidate_index = ", first_candidate_index.value(),
263 "\ncandidate_for_recursion = ", candidate_for_recursion.value());
264 return buffer;
265 }
266
267 // The pivot node selected for the given level of the recursion.
268 NodeIndex pivot;
269 // The number of remaining candidates to be explored at the given level of
270 // the recursion; the number is computed as num_disconnected_nodes +
271 // pre_increment in the original algorithm.
272 int num_remaining_candidates;
273 // The list of nodes that are candidates for extending the current clique.
274 // This vector has the format proposed in the paper by Bron-Kerbosch; the
275 // first 'first_candidate_index' elements of the vector represent the
276 // "not" set of nodes that were already visited by the algorithm. The
277 // remaining elements are the actual candidates for extending the current
278 // clique.
279 // NOTE(user): We could store the delta between the iterations; however,
280 // we need to evaluate the impact this would have on the performance.
281 util_intops::StrongVector<CandidateIndex, NodeIndex> candidates;
282 // The index of the first actual candidate in 'candidates'. This number is
283 // also the number of elements of the "not" set stored at the beginning of
284 // 'candidates'.
285 CandidateIndex first_candidate_index;
286
287 // The current position in candidates when looking for the pivot and/or the
288 // next candidate disconnected from the pivot.
289 CandidateIndex candidate_for_recursion;
290 };
291
292 // The deterministic time coefficients for the push and pop operations of the
293 // Bron-Kerbosch algorithm. The coefficients are set to match approximately
294 // the running time in seconds on a recent workstation on the random graph
295 // benchmark.
296 // NOTE(user): PushState is not the only source of complexity in the
297 // algorithm, but non-negative linear least squares produced zero coefficients
298 // for all other deterministic counters tested during the benchmarking. When
299 // we optimize the algorithm, we might need to add deterministic time to the
300 // other places that may produce complexity, namely InitializeState, PopState
301 // and SelectCandidateIndexForRecursion.
302 static const double kPushStateDeterministicTimeSecondsPerCandidate;
303
304 // Initializes the root state of the algorithm.
305 void Initialize();
306
307 // Removes the top state from the state stack. This is equivalent to returning
308 // in the recursive implementation of the algorithm.
309 void PopState();
310
311 // Adds a new state to the top of the stack, adding the node 'selected' to the
312 // current clique. This is equivalent to making a recurisve call in the
313 // recursive implementation of the algorithm.
314 void PushState(NodeIndex selected);
315
316 // Initializes the given state. Runs the pivot selection algorithm in the
317 // state.
318 void InitializeState(State* state);
319
320 // Returns true if (node1, node2) is an arc in the graph or if node1 == node2.
321 inline bool IsArc(NodeIndex node1, NodeIndex node2) const {
322 return node1 == node2 || is_arc_(node1, node2);
323 }
324
325 // Selects the next node for recursion. The selected node is either the pivot
326 // (if it is not in the set "not") or a node that is disconnected from the
327 // pivot.
328 CandidateIndex SelectCandidateIndexForRecursion(State* state);
329
330 // Returns a human-readable string representation of the clique.
331 std::string CliqueDebugString(const std::vector<NodeIndex>& clique);
332
333 // The callback called when the algorithm needs to determine if (node1, node2)
334 // is an arc in the graph.
335 IsArcCallback is_arc_;
336
337 // The callback called when the algorithm discovers a maximal clique. The
338 // return value of the callback controls how the algorithm proceeds with the
339 // clique search.
340 CliqueCallback clique_callback_;
341
342 // The number of nodes in the graph.
343 const NodeIndex num_nodes_;
344
345 // Contains the state of the aglorithm. The vector serves as an external stack
346 // for the recursive part of the algorithm - instead of using the C++ stack
347 // and natural recursion, it is implemented as a loop and new states are added
348 // to the top of the stack. The algorithm ends when the stack is empty.
349 std::vector<State> states_;
350
351 // A vector that receives the current clique found by the algorithm.
352 std::vector<NodeIndex> current_clique_;
353
354 // Set to true if the algorithm is active (it was not stopped by a the clique
355 // callback).
356 int64_t num_remaining_iterations_;
357
358 // The current time limit used by the solver. The time limit is assigned by
359 // the Run methods and it can be different for each call to run.
360 TimeLimit* time_limit_;
361};
362
363// More specialized version used to separate clique-cuts in MIP solver.
364// This finds all maximal clique with a weight greater than a given threshold.
365// It also has computation limit.
366//
367// This implementation assumes small graph since we use a dense bitmask
368// representation to encode the graph adjacency. So it shouldn't really be used
369// with more than a few thousands nodes.
371 public:
372 // Resets the class to an empty graph will all weights of zero.
373 // This also reset the work done.
374 void Initialize(int num_nodes);
375
376 // Set the weight of a given node, must be in [0, num_nodes).
377 // Weights are assumed to be non-negative.
378 void SetWeight(int i, double weight) { weights_[i] = weight; }
379
380 // Add an edge in the graph.
381 void AddEdge(int a, int b) {
382 graph_[a].Set(b);
383 graph_[b].Set(a);
384 }
385
386 // We count the number of basic operations, and stop when we reach this limit.
387 void SetWorkLimit(int64_t limit) { work_limit_ = limit; }
388
389 // Set the minimum weight of the maximal cliques we are looking for.
390 void SetMinimumWeight(double min_weight) { weight_threshold_ = min_weight; }
391
392 // This function is quite specific. It interprets node i as the negated
393 // literal of node i ^ 1. And all j in graph[i] as literal that are in at most
394 // two relation. So i implies all not(j) for all j in graph[i].
395 //
396 // The transitive close runs in O(num_nodes ^ 3) in the worst case, but since
397 // we process 64 bits at the time, it is okay to run it for graph up to 1k
398 // nodes.
400
401 // Runs the algo and returns all maximal clique with a weight above the
402 // configured thrheshold via SetMinimumWeight(). It is possible we reach the
403 // work limit before that.
404 std::vector<std::vector<int>> Run();
405
406 // Specific API where the index refer in the last result of Run().
407 // This allows to select cliques when they are many.
408 std::vector<std::pair<int, double>>& GetMutableIndexAndWeight() {
409 return clique_index_and_weight_;
410 }
411
412 int64_t WorkDone() const { return work_; }
413
414 bool HasEdge(int i, int j) const { return graph_[i][j]; }
415
416 private:
417 int64_t work_ = 0;
418 int64_t work_limit_ = std::numeric_limits<int64_t>::max();
419 double weight_threshold_ = 0.0;
420
421 std::vector<double> weights_;
422 std::vector<Bitset64<int>> graph_;
423
424 // Iterative DFS queue.
425 std::vector<int> queue_;
426
427 // Current clique we are constructing.
428 // Note this is always of size num_nodes, the clique is in [0, depth)
429 Bitset64<int> in_clique_;
430 std::vector<int> clique_;
431
432 // We maintain the weight of the clique. We use a stack to avoid floating
433 // point issue with +/- weights many times. So clique_weight_[i] is the sum of
434 // weight from [0, i) of element of the cliques.
435 std::vector<double> clique_weight_;
436
437 // Correspond to P and X in BronKerbosch description.
438 std::vector<Bitset64<int>> left_to_process_;
439 std::vector<Bitset64<int>> x_;
440
441 std::vector<std::pair<int, double>> clique_index_and_weight_;
442};
443
444template <typename NodeIndex>
445void BronKerboschAlgorithm<NodeIndex>::InitializeState(State* state) {
446 DCHECK(state != nullptr);
447 const int num_candidates = state->candidates.size();
448 int num_disconnected_candidates = num_candidates;
449 state->pivot = 0;
450 CandidateIndex pivot_index(-1);
451 for (CandidateIndex pivot_candidate_index(0);
452 pivot_candidate_index < num_candidates &&
453 num_disconnected_candidates > 0;
454 ++pivot_candidate_index) {
455 const NodeIndex pivot_candidate = state->candidates[pivot_candidate_index];
456 int count = 0;
457 for (CandidateIndex i(state->first_candidate_index); i < num_candidates;
458 ++i) {
459 if (!IsArc(pivot_candidate, state->candidates[i])) {
460 ++count;
461 }
462 }
463 if (count < num_disconnected_candidates) {
464 pivot_index = pivot_candidate_index;
465 state->pivot = pivot_candidate;
466 num_disconnected_candidates = count;
467 }
468 }
469 state->num_remaining_candidates = num_disconnected_candidates;
470 if (pivot_index >= state->first_candidate_index) {
471 std::swap(state->candidates[pivot_index],
472 state->candidates[state->first_candidate_index]);
473 ++state->num_remaining_candidates;
474 }
475}
476
477template <typename NodeIndex>
479BronKerboschAlgorithm<NodeIndex>::SelectCandidateIndexForRecursion(
480 State* state) {
481 DCHECK(state != nullptr);
482 CandidateIndex disconnected_node_index =
483 std::max(state->first_candidate_index, state->candidate_for_recursion);
484 while (disconnected_node_index < state->candidates.size() &&
485 state->candidates[disconnected_node_index] != state->pivot &&
486 IsArc(state->pivot, state->candidates[disconnected_node_index])) {
487 ++disconnected_node_index;
488 }
489 state->candidate_for_recursion = disconnected_node_index;
490 return disconnected_node_index;
491}
492
493template <typename NodeIndex>
494void BronKerboschAlgorithm<NodeIndex>::Initialize() {
495 DCHECK(states_.empty());
496 states_.reserve(num_nodes_);
497 states_.emplace_back();
498
499 State* const root_state = &states_.back();
500 root_state->first_candidate_index = 0;
501 root_state->candidate_for_recursion = 0;
502 root_state->candidates.resize(num_nodes_, 0);
503 std::iota(root_state->candidates.begin(), root_state->candidates.end(), 0);
504 root_state->num_remaining_candidates = num_nodes_;
505 InitializeState(root_state);
506
507 DVLOG(2) << "Initialized";
508}
509
510template <typename NodeIndex>
511void BronKerboschAlgorithm<NodeIndex>::PopState() {
512 DCHECK(!states_.empty());
513 states_.pop_back();
514 if (!states_.empty()) {
515 State* const state = &states_.back();
516 current_clique_.pop_back();
517 state->MoveFirstCandidateToNotSet();
518 }
519}
520
521template <typename NodeIndex>
522std::string BronKerboschAlgorithm<NodeIndex>::CliqueDebugString(
523 const std::vector<NodeIndex>& clique) {
524 std::string message = "Clique: [ ";
525 for (const NodeIndex node : clique) {
526 absl::StrAppend(&message, node, " ");
527 }
528 message += "]";
529 return message;
530}
531
532template <typename NodeIndex>
533void BronKerboschAlgorithm<NodeIndex>::PushState(NodeIndex selected) {
534 DCHECK(!states_.empty());
535 DCHECK(time_limit_ != nullptr);
536 DVLOG(2) << "PushState: New depth = " << states_.size() + 1
537 << ", selected node = " << selected;
538 util_intops::StrongVector<CandidateIndex, NodeIndex> new_candidates;
539
540 State* const previous_state = &states_.back();
541 const double deterministic_time =
543 previous_state->candidates.size();
544 time_limit_->AdvanceDeterministicTime(deterministic_time, "PushState");
545
546 // Add all candidates from previous_state->candidates that are connected to
547 // 'selected' in the graph to the vector 'new_candidates', skipping the node
548 // 'selected'; this node is always at the position
549 // 'previous_state->first_candidate_index', so we can skip it by skipping the
550 // element at this particular index.
551 new_candidates.reserve(previous_state->candidates.size());
552 for (CandidateIndex i(0); i < previous_state->first_candidate_index; ++i) {
553 const NodeIndex candidate = previous_state->candidates[i];
554 if (IsArc(selected, candidate)) {
555 new_candidates.push_back(candidate);
556 }
557 }
558 const CandidateIndex new_first_candidate_index(new_candidates.size());
559 for (CandidateIndex i = previous_state->first_candidate_index + 1;
560 i < previous_state->candidates.size(); ++i) {
561 const NodeIndex candidate = previous_state->candidates[i];
562 if (IsArc(selected, candidate)) {
563 new_candidates.push_back(candidate);
564 }
565 }
566
567 current_clique_.push_back(selected);
568 if (new_candidates.empty()) {
569 // We've found a clique. Report it to the user, but do not push the state
570 // because it would be popped immediately anyway.
571 DVLOG(2) << CliqueDebugString(current_clique_);
572 const CliqueResponse response = clique_callback_(current_clique_);
573 if (response == CliqueResponse::STOP) {
574 // The number of remaining iterations will be decremented at the end of
575 // the loop in RunIterations; setting it to 0 here would make it -1 at
576 // the end of the main loop.
577 num_remaining_iterations_ = 1;
578 }
579 current_clique_.pop_back();
580 previous_state->MoveFirstCandidateToNotSet();
581 return;
582 }
583
584 // NOTE(user): The following line may invalidate previous_state (if the
585 // vector data was re-allocated in the process). We must avoid using
586 // previous_state below here.
587 states_.emplace_back();
588 State* const new_state = &states_.back();
589 new_state->candidates.swap(new_candidates);
590 new_state->first_candidate_index = new_first_candidate_index;
591
592 InitializeState(new_state);
593}
594
595template <typename NodeIndex>
597 int64_t max_num_iterations, TimeLimit* time_limit) {
598 CHECK(time_limit != nullptr);
599 time_limit_ = time_limit;
600 if (states_.empty()) {
601 Initialize();
602 }
603 for (num_remaining_iterations_ = max_num_iterations;
604 !states_.empty() && num_remaining_iterations_ > 0 &&
605 !time_limit->LimitReached();
606 --num_remaining_iterations_) {
607 State* const state = &states_.back();
608 DVLOG(2) << "Loop: " << states_.size() << " states, "
609 << state->num_remaining_candidates << " candidate to explore\n"
610 << state->DebugString();
611 if (state->num_remaining_candidates == 0) {
612 PopState();
613 continue;
614 }
615
616 const CandidateIndex selected_index =
617 SelectCandidateIndexForRecursion(state);
618 DVLOG(2) << "selected_index = " << selected_index;
619 const NodeIndex selected = state->candidates[selected_index];
620 DVLOG(2) << "Selected candidate = " << selected;
621
622 NodeIndex& f = state->candidates[state->first_candidate_index];
623 NodeIndex& s = state->candidates[selected_index];
624 std::swap(f, s);
625
626 PushState(selected);
627 }
628 time_limit_ = nullptr;
629 return states_.empty() ? BronKerboschAlgorithmStatus::COMPLETED
631}
632
633template <typename NodeIndex>
635 int64_t max_num_iterations) {
636 TimeLimit time_limit(std::numeric_limits<double>::infinity());
637 return RunWithTimeLimit(max_num_iterations, &time_limit);
638}
639
640template <typename NodeIndex>
642 return RunIterations(std::numeric_limits<int64_t>::max());
643}
644
645template <typename NodeIndex>
646const double BronKerboschAlgorithm<
648} // namespace operations_research
649
650#endif // OR_TOOLS_GRAPH_CLIQUES_H_
std::function< bool(NodeIndex, NodeIndex)> IsArcCallback
Definition cliques.h:156
BronKerboschAlgorithmStatus RunWithTimeLimit(TimeLimit *time_limit)
Definition cliques.h:210
BronKerboschAlgorithmStatus Run()
Definition cliques.h:641
std::function< CliqueResponse(const std::vector< NodeIndex > &)> CliqueCallback
Definition cliques.h:165
BronKerboschAlgorithm(IsArcCallback is_arc, NodeIndex num_nodes, CliqueCallback clique_callback)
Definition cliques.h:170
BronKerboschAlgorithmStatus RunIterations(int64_t max_num_iterations)
Definition cliques.h:634
BronKerboschAlgorithmStatus RunWithTimeLimit(int64_t max_num_iterations, TimeLimit *time_limit)
Definition cliques.h:596
void SetMinimumWeight(double min_weight)
Set the minimum weight of the maximal cliques we are looking for.
Definition cliques.h:390
std::vector< std::pair< int, double > > & GetMutableIndexAndWeight()
Definition cliques.h:408
void AddEdge(int a, int b)
Add an edge in the graph.
Definition cliques.h:381
std::vector< std::vector< int > > Run()
Definition cliques.cc:298
void SetWorkLimit(int64_t limit)
We count the number of basic operations, and stop when we reach this limit.
Definition cliques.h:387
void push_back(const value_type &val)
void reserve(size_type n)
#define DEFINE_INT_TYPE(int_type_name, value_type)
Definition int_type.h:167
time_limit
Definition solve.cc:22
In SWIG mode, we don't want anything besides these top-level includes.
void FindCliques(std::function< bool(int, int)> graph, int node_count, std::function< bool(const std::vector< int > &)> callback)
Definition cliques.cc:230
@ COMPLETED
The algorithm has enumerated all maximal cliques.
Definition cliques.h:76
const double BronKerboschAlgorithm< NodeIndex >::kPushStateDeterministicTimeSecondsPerCandidate
Definition cliques.h:647
@ CONTINUE
The algorithm will continue searching for other maximal cliques.
Definition cliques.h:66
void CoverArcsByCliques(std::function< bool(int, int)> graph, int node_count, std::function< bool(const std::vector< int > &)> callback)
Definition cliques.cc:244
STL namespace.