Files
ortools-clone/examples/cpp/nqueens.cc

284 lines
9.3 KiB
C++
Raw Permalink Normal View History

2025-01-10 11:35:44 +01:00
// Copyright 2010-2025 Google LLC
2010-09-15 12:42:33 +00:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2010-09-15 12:42:33 +00:00
// N-queens problem
//
// unique solutions: http://www.research.att.com/~njas/sequences/A000170
// distinct solutions: http://www.research.att.com/~njas/sequences/A002562
2021-04-23 14:55:51 +02:00
#include <cstdint>
#include <cstdio>
#include <map>
2023-01-31 20:46:43 +01:00
#include <vector>
2021-04-23 14:55:51 +02:00
#include "absl/container/flat_hash_map.h"
dotnet: Remove reference to dotnet release command - Currently not implemented... Add abseil patch - Add patches/absl-config.cmake Makefile: Add abseil-cpp on unix - Force abseil-cpp SHA1 to 45221cc note: Just before the PR #136 which break all CMake Makefile: Add abseil-cpp on windows - Force abseil-cpp SHA1 to 45221cc note: Just before the PR #136 which break all CMake CMake: Add abseil-cpp - Force abseil-cpp SHA1 to 45221cc note: Just before the PR #136 which break all CMake port to absl: C++ Part - Fix warning with the use of ABSL_MUST_USE_RESULT > The macro must appear as the very first part of a function declaration or definition: ... Note: past advice was to place the macro after the argument list. src: dependencies/sources/abseil-cpp-master/absl/base/attributes.h:418 - Rename enum after windows clash - Remove non compact table constraints - Change index type from int64 to int in routing library - Fix file_nonport compilation on windows - Fix another naming conflict with windows (NO_ERROR is a macro) - Cleanup hash containers; work on sat internals - Add optional_boolean sub-proto Sync cpp examples with internal code - reenable issue173 after reducing number of loops port to absl: Python Part - Add back cp_model.INT32_MIN|MAX for examples Update Python examples - Add random_tsp.py - Run words_square example - Run magic_square in python tests port to absl: Java Part - Fix compilation of the new routing parameters in java - Protect some code from SWIG parsing Update Java Examples port to absl: .Net Part Update .Net examples work on sat internals; Add C++ CP-SAT CpModelBuilder API; update sample code and recipes to use the new API; sync with internal code Remove VS 2015 in Appveyor-CI - abseil-cpp does not support VS 2015... improve tables upgrade C++ sat examples to use the new API; work on sat internals update license dates rewrite jobshop_ft06_distance.py to use the CP-SAT solver rename last example revert last commit more work on SAT internals fix
2018-10-31 16:18:18 +01:00
#include "absl/strings/str_format.h"
#include "ortools/base/commandlineflags.h"
2022-02-25 09:47:52 +01:00
#include "ortools/base/init_google.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/base/types.h"
2025-03-24 04:53:51 -07:00
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
2010-09-15 12:42:33 +00:00
2020-10-23 11:50:14 +02:00
ABSL_FLAG(bool, print, false, "If true, print one of the solution.");
ABSL_FLAG(bool, print_all, false, "If true, print all the solutions.");
ABSL_FLAG(int, nb_loops, 1,
"Number of solving loops to perform, for performance timing.");
ABSL_FLAG(
int, size, 0,
2014-01-08 12:01:58 +00:00
"Size of the problem. If equal to 0, will test several increasing sizes.");
2020-10-23 11:50:14 +02:00
ABSL_FLAG(bool, use_symmetry, false, "Use Symmetry Breaking methods");
2010-09-15 12:42:33 +00:00
2020-10-22 23:36:58 +02:00
static const int kNumSolutions[] = {
1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712, 365596, 2279184};
2010-09-15 12:42:33 +00:00
static const int kKnownSolutions = 15;
2020-10-22 23:36:58 +02:00
static const int kNumUniqueSolutions[] = {
1, 0, 0, 1, 2, 1, 6, 12, 46, 92,
341, 1787, 9233, 45752, 285053, 1846955, 11977939, 83263591, 621012754};
2010-09-15 12:42:33 +00:00
static const int kKnownUniqueSolutions = 19;
namespace operations_research {
class NQueenSymmetry : public SymmetryBreaker {
2020-10-22 23:36:58 +02:00
public:
2020-10-29 14:25:39 +01:00
NQueenSymmetry(Solver* const s, const std::vector<IntVar*>& vars)
2010-09-15 12:42:33 +00:00
: solver_(s), vars_(vars), size_(vars.size()) {
for (int i = 0; i < size_; ++i) {
indices_[vars[i]] = i;
}
}
~NQueenSymmetry() override = default;
2011-06-15 09:56:44 +00:00
2020-10-22 23:36:58 +02:00
protected:
2020-10-29 14:25:39 +01:00
int Index(IntVar* const var) const {
return gtl::FindWithDefault(indices_, var, -1);
2010-09-15 12:42:33 +00:00
}
2020-10-29 14:25:39 +01:00
IntVar* Var(int index) const {
2010-09-15 12:42:33 +00:00
DCHECK_GE(index, 0);
DCHECK_LT(index, size_);
return vars_[index];
}
int size() const { return size_; }
2011-06-15 09:56:44 +00:00
int symmetric(int index) const { return size_ - 1 - index; }
Solver* solver() const { return solver_; }
2011-06-10 20:00:27 +00:00
2020-10-22 23:36:58 +02:00
private:
2020-10-29 14:25:39 +01:00
Solver* const solver_;
const std::vector<IntVar*> vars_;
2021-04-23 14:55:51 +02:00
absl::flat_hash_map<const IntVar*, int> indices_;
2010-09-15 12:42:33 +00:00
const int size_;
};
// Symmetry vertical axis.
class SX : public NQueenSymmetry {
2020-10-22 23:36:58 +02:00
public:
2020-10-29 14:25:39 +01:00
SX(Solver* const s, const std::vector<IntVar*>& vars)
: NQueenSymmetry(s, vars) {}
~SX() override = default;
2010-09-15 12:42:33 +00:00
2021-04-02 14:58:16 +02:00
void VisitSetVariableValue(IntVar* const var, int64_t value) override {
2010-09-15 12:42:33 +00:00
const int index = Index(var);
2020-10-29 14:25:39 +01:00
IntVar* const other_var = Var(symmetric(index));
2011-06-08 14:10:19 +00:00
AddIntegerVariableEqualValueClause(other_var, value);
2010-09-15 12:42:33 +00:00
}
};
// Symmetry horizontal axis.
class SY : public NQueenSymmetry {
2020-10-22 23:36:58 +02:00
public:
2020-10-29 14:25:39 +01:00
SY(Solver* const s, const std::vector<IntVar*>& vars)
: NQueenSymmetry(s, vars) {}
~SY() override = default;
2010-09-15 12:42:33 +00:00
2021-04-02 14:58:16 +02:00
void VisitSetVariableValue(IntVar* const var, int64_t value) override {
2011-06-08 14:10:19 +00:00
AddIntegerVariableEqualValueClause(var, symmetric(value));
2010-09-15 12:42:33 +00:00
}
};
2010-09-25 21:28:12 +00:00
// Symmetry first diagonal axis.
2010-09-15 12:42:33 +00:00
class SD1 : public NQueenSymmetry {
2020-10-22 23:36:58 +02:00
public:
2020-10-29 14:25:39 +01:00
SD1(Solver* const s, const std::vector<IntVar*>& vars)
: NQueenSymmetry(s, vars) {}
~SD1() override = default;
2010-09-15 12:42:33 +00:00
2021-04-02 14:58:16 +02:00
void VisitSetVariableValue(IntVar* const var, int64_t value) override {
2010-09-15 12:42:33 +00:00
const int index = Index(var);
2020-10-29 14:25:39 +01:00
IntVar* const other_var = Var(value);
2011-06-08 14:10:19 +00:00
AddIntegerVariableEqualValueClause(other_var, index);
2010-09-15 12:42:33 +00:00
}
};
// Symmetry second diagonal axis.
class SD2 : public NQueenSymmetry {
2020-10-22 23:36:58 +02:00
public:
2020-10-29 14:25:39 +01:00
SD2(Solver* const s, const std::vector<IntVar*>& vars)
: NQueenSymmetry(s, vars) {}
~SD2() override = default;
2010-09-15 12:42:33 +00:00
2021-04-02 14:58:16 +02:00
void VisitSetVariableValue(IntVar* const var, int64_t value) override {
2010-09-15 12:42:33 +00:00
const int index = Index(var);
2020-10-29 14:25:39 +01:00
IntVar* const other_var = Var(symmetric(value));
2011-06-08 14:10:19 +00:00
AddIntegerVariableEqualValueClause(other_var, symmetric(index));
2010-09-15 12:42:33 +00:00
}
};
// Rotate 1/4 turn.
class R90 : public NQueenSymmetry {
2020-10-22 23:36:58 +02:00
public:
2020-10-29 14:25:39 +01:00
R90(Solver* const s, const std::vector<IntVar*>& vars)
: NQueenSymmetry(s, vars) {}
~R90() override = default;
2010-09-15 12:42:33 +00:00
2021-04-02 14:58:16 +02:00
void VisitSetVariableValue(IntVar* const var, int64_t value) override {
2010-09-15 12:42:33 +00:00
const int index = Index(var);
2020-10-29 14:25:39 +01:00
IntVar* const other_var = Var(value);
2011-06-08 14:10:19 +00:00
AddIntegerVariableEqualValueClause(other_var, symmetric(index));
2010-09-15 12:42:33 +00:00
}
};
// Rotate 1/2 turn.
class R180 : public NQueenSymmetry {
2020-10-22 23:36:58 +02:00
public:
2020-10-29 14:25:39 +01:00
R180(Solver* const s, const std::vector<IntVar*>& vars)
2010-09-15 12:42:33 +00:00
: NQueenSymmetry(s, vars) {}
~R180() override = default;
2010-09-15 12:42:33 +00:00
2021-04-02 14:58:16 +02:00
void VisitSetVariableValue(IntVar* const var, int64_t value) override {
2010-09-15 12:42:33 +00:00
const int index = Index(var);
2020-10-29 14:25:39 +01:00
IntVar* const other_var = Var(symmetric(index));
2011-06-08 14:10:19 +00:00
AddIntegerVariableEqualValueClause(other_var, symmetric(value));
2010-09-15 12:42:33 +00:00
}
};
// Rotate 3/4 turn.
class R270 : public NQueenSymmetry {
2020-10-22 23:36:58 +02:00
public:
2020-10-29 14:25:39 +01:00
R270(Solver* const s, const std::vector<IntVar*>& vars)
2010-09-15 12:42:33 +00:00
: NQueenSymmetry(s, vars) {}
~R270() override = default;
2010-09-15 12:42:33 +00:00
2021-04-02 14:58:16 +02:00
void VisitSetVariableValue(IntVar* const var, int64_t value) override {
2010-09-15 12:42:33 +00:00
const int index = Index(var);
2020-10-29 14:25:39 +01:00
IntVar* const other_var = Var(symmetric(value));
2011-06-08 14:10:19 +00:00
AddIntegerVariableEqualValueClause(other_var, index);
2010-09-15 12:42:33 +00:00
}
};
2011-09-08 00:34:28 +00:00
void CheckNumberOfSolutions(int size, int num_solutions) {
if (absl::GetFlag(FLAGS_use_symmetry)) {
2011-09-08 00:34:28 +00:00
if (size - 1 < kKnownUniqueSolutions) {
CHECK_EQ(num_solutions, kNumUniqueSolutions[size - 1]);
2025-03-24 04:53:51 -07:00
} else if (!absl::GetFlag(FLAGS_cp_disable_solve)) {
CHECK_GT(num_solutions, 0);
2011-09-08 00:34:28 +00:00
}
} else {
if (size - 1 < kKnownSolutions) {
CHECK_EQ(num_solutions, kNumSolutions[size - 1]);
2025-03-24 04:53:51 -07:00
} else if (!absl::GetFlag(FLAGS_cp_disable_solve)) {
CHECK_GT(num_solutions, 0);
2011-09-08 00:34:28 +00:00
}
}
}
2010-09-15 12:42:33 +00:00
void NQueens(int size) {
CHECK_GE(size, 1);
2010-09-25 21:28:12 +00:00
Solver s("nqueens");
2010-09-15 12:42:33 +00:00
// model
2020-10-29 14:25:39 +01:00
std::vector<IntVar*> queens;
2010-09-15 12:42:33 +00:00
for (int i = 0; i < size; ++i) {
dotnet: Remove reference to dotnet release command - Currently not implemented... Add abseil patch - Add patches/absl-config.cmake Makefile: Add abseil-cpp on unix - Force abseil-cpp SHA1 to 45221cc note: Just before the PR #136 which break all CMake Makefile: Add abseil-cpp on windows - Force abseil-cpp SHA1 to 45221cc note: Just before the PR #136 which break all CMake CMake: Add abseil-cpp - Force abseil-cpp SHA1 to 45221cc note: Just before the PR #136 which break all CMake port to absl: C++ Part - Fix warning with the use of ABSL_MUST_USE_RESULT > The macro must appear as the very first part of a function declaration or definition: ... Note: past advice was to place the macro after the argument list. src: dependencies/sources/abseil-cpp-master/absl/base/attributes.h:418 - Rename enum after windows clash - Remove non compact table constraints - Change index type from int64 to int in routing library - Fix file_nonport compilation on windows - Fix another naming conflict with windows (NO_ERROR is a macro) - Cleanup hash containers; work on sat internals - Add optional_boolean sub-proto Sync cpp examples with internal code - reenable issue173 after reducing number of loops port to absl: Python Part - Add back cp_model.INT32_MIN|MAX for examples Update Python examples - Add random_tsp.py - Run words_square example - Run magic_square in python tests port to absl: Java Part - Fix compilation of the new routing parameters in java - Protect some code from SWIG parsing Update Java Examples port to absl: .Net Part Update .Net examples work on sat internals; Add C++ CP-SAT CpModelBuilder API; update sample code and recipes to use the new API; sync with internal code Remove VS 2015 in Appveyor-CI - abseil-cpp does not support VS 2015... improve tables upgrade C++ sat examples to use the new API; work on sat internals update license dates rewrite jobshop_ft06_distance.py to use the CP-SAT solver rename last example revert last commit more work on SAT internals fix
2018-10-31 16:18:18 +01:00
queens.push_back(
s.MakeIntVar(0, size - 1, absl::StrFormat("queen%04d", i)));
2010-09-15 12:42:33 +00:00
}
s.AddConstraint(s.MakeAllDifferent(queens));
2010-09-15 12:42:33 +00:00
2020-10-29 14:25:39 +01:00
std::vector<IntVar*> vars(size);
2010-09-15 12:42:33 +00:00
for (int i = 0; i < size; ++i) {
2010-09-25 21:28:12 +00:00
vars[i] = s.MakeSum(queens[i], i)->Var();
2010-09-15 12:42:33 +00:00
}
s.AddConstraint(s.MakeAllDifferent(vars));
2010-09-15 12:42:33 +00:00
for (int i = 0; i < size; ++i) {
2010-09-25 21:28:12 +00:00
vars[i] = s.MakeSum(queens[i], -i)->Var();
2010-09-15 12:42:33 +00:00
}
s.AddConstraint(s.MakeAllDifferent(vars));
2010-09-15 12:42:33 +00:00
2020-10-29 14:25:39 +01:00
SolutionCollector* const solution_counter =
s.MakeAllSolutionCollector(nullptr);
2020-10-29 14:25:39 +01:00
SolutionCollector* const collector = s.MakeAllSolutionCollector();
collector->Add(queens);
2020-10-29 14:25:39 +01:00
std::vector<SearchMonitor*> monitors;
monitors.push_back(solution_counter);
monitors.push_back(collector);
2020-10-29 14:25:39 +01:00
DecisionBuilder* const db = s.MakePhase(queens, Solver::CHOOSE_FIRST_UNBOUND,
2010-09-25 21:28:12 +00:00
Solver::ASSIGN_MIN_VALUE);
if (absl::GetFlag(FLAGS_use_symmetry)) {
2020-10-29 14:25:39 +01:00
std::vector<SymmetryBreaker*> breakers;
NQueenSymmetry* const sx = s.RevAlloc(new SX(&s, queens));
2010-09-15 12:42:33 +00:00
breakers.push_back(sx);
2020-10-29 14:25:39 +01:00
NQueenSymmetry* const sy = s.RevAlloc(new SY(&s, queens));
2010-09-15 12:42:33 +00:00
breakers.push_back(sy);
2020-10-29 14:25:39 +01:00
NQueenSymmetry* const sd1 = s.RevAlloc(new SD1(&s, queens));
2010-09-15 12:42:33 +00:00
breakers.push_back(sd1);
2020-10-29 14:25:39 +01:00
NQueenSymmetry* const sd2 = s.RevAlloc(new SD2(&s, queens));
2010-09-15 12:42:33 +00:00
breakers.push_back(sd2);
2020-10-29 14:25:39 +01:00
NQueenSymmetry* const r90 = s.RevAlloc(new R90(&s, queens));
2010-09-15 12:42:33 +00:00
breakers.push_back(r90);
2020-10-29 14:25:39 +01:00
NQueenSymmetry* const r180 = s.RevAlloc(new R180(&s, queens));
2010-09-15 12:42:33 +00:00
breakers.push_back(r180);
2020-10-29 14:25:39 +01:00
NQueenSymmetry* const r270 = s.RevAlloc(new R270(&s, queens));
2010-09-15 12:42:33 +00:00
breakers.push_back(r270);
2020-10-29 14:25:39 +01:00
SearchMonitor* const symmetry_manager = s.MakeSymmetryManager(breakers);
2010-09-15 12:42:33 +00:00
monitors.push_back(symmetry_manager);
}
for (int loop = 0; loop < absl::GetFlag(FLAGS_nb_loops); ++loop) {
2020-10-22 23:36:58 +02:00
s.Solve(db, monitors); // go!
2011-09-08 00:34:28 +00:00
CheckNumberOfSolutions(size, solution_counter->solution_count());
2010-09-15 12:42:33 +00:00
}
const int num_solutions = solution_counter->solution_count();
2010-09-15 12:42:33 +00:00
if (num_solutions > 0 && size < kKnownSolutions) {
2020-10-29 14:25:39 +01:00
int print_max = absl::GetFlag(FLAGS_print_all) ? num_solutions
: absl::GetFlag(FLAGS_print) ? 1
: 0;
2010-09-15 12:42:33 +00:00
for (int n = 0; n < print_max; ++n) {
2021-04-23 14:55:51 +02:00
absl::PrintF("--- solution #%d\n", n);
2010-09-15 12:42:33 +00:00
for (int i = 0; i < size; ++i) {
const int pos = static_cast<int>(collector->Value(n, queens[i]));
2021-04-23 14:55:51 +02:00
for (int k = 0; k < pos; ++k) absl::PrintF(" . ");
absl::PrintF("%2d ", i);
for (int k = pos + 1; k < size; ++k) absl::PrintF(" . ");
absl::PrintF("\n");
2010-09-15 12:42:33 +00:00
}
}
}
2021-04-23 14:55:51 +02:00
absl::PrintF("========= number of solutions:%d\n", num_solutions);
dotnet: Remove reference to dotnet release command - Currently not implemented... Add abseil patch - Add patches/absl-config.cmake Makefile: Add abseil-cpp on unix - Force abseil-cpp SHA1 to 45221cc note: Just before the PR #136 which break all CMake Makefile: Add abseil-cpp on windows - Force abseil-cpp SHA1 to 45221cc note: Just before the PR #136 which break all CMake CMake: Add abseil-cpp - Force abseil-cpp SHA1 to 45221cc note: Just before the PR #136 which break all CMake port to absl: C++ Part - Fix warning with the use of ABSL_MUST_USE_RESULT > The macro must appear as the very first part of a function declaration or definition: ... Note: past advice was to place the macro after the argument list. src: dependencies/sources/abseil-cpp-master/absl/base/attributes.h:418 - Rename enum after windows clash - Remove non compact table constraints - Change index type from int64 to int in routing library - Fix file_nonport compilation on windows - Fix another naming conflict with windows (NO_ERROR is a macro) - Cleanup hash containers; work on sat internals - Add optional_boolean sub-proto Sync cpp examples with internal code - reenable issue173 after reducing number of loops port to absl: Python Part - Add back cp_model.INT32_MIN|MAX for examples Update Python examples - Add random_tsp.py - Run words_square example - Run magic_square in python tests port to absl: Java Part - Fix compilation of the new routing parameters in java - Protect some code from SWIG parsing Update Java Examples port to absl: .Net Part Update .Net examples work on sat internals; Add C++ CP-SAT CpModelBuilder API; update sample code and recipes to use the new API; sync with internal code Remove VS 2015 in Appveyor-CI - abseil-cpp does not support VS 2015... improve tables upgrade C++ sat examples to use the new API; work on sat internals update license dates rewrite jobshop_ft06_distance.py to use the CP-SAT solver rename last example revert last commit more work on SAT internals fix
2018-10-31 16:18:18 +01:00
absl::PrintF(" number of failures: %d\n", s.failures());
2010-09-15 12:42:33 +00:00
}
2020-10-22 23:36:58 +02:00
} // namespace operations_research
2010-09-15 12:42:33 +00:00
2020-10-29 14:25:39 +01:00
int main(int argc, char** argv) {
2022-02-25 09:47:52 +01:00
InitGoogle(argv[0], &argc, &argv, true);
if (absl::GetFlag(FLAGS_size) != 0) {
operations_research::NQueens(absl::GetFlag(FLAGS_size));
2010-09-15 12:42:33 +00:00
} else {
for (int n = 1; n < 12; ++n) {
operations_research::NQueens(n);
}
}
2022-02-25 09:47:52 +01:00
return 0;
2010-09-15 12:42:33 +00:00
}