Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
backtracking_nqueens_example.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
46#include <iostream>
47#include <string>
48
49#include <State_Search.H>
50#include <tpl_array.H>
51
52using Aleph::Array;
53
54namespace
55{
56
57namespace Search = Aleph::Search;
58
59struct NQueensState
60{
61 size_t n = 0;
62 size_t row = 0;
63 Array<int> queens;
64 Array<unsigned char> used_columns;
65 Array<unsigned char> used_diag_down;
66 Array<unsigned char> used_diag_up;
67
68 explicit NQueensState(const size_t size = 0)
69 : n(size),
70 row(0),
71 queens(size, -1),
72 used_columns(size, 0),
73 used_diag_down(size == 0 ? 0 : 2*size - 1, 0),
74 used_diag_up(size == 0 ? 0 : 2*size - 1, 0)
75 {
76 // empty
77 }
78};
79
80struct NQueensDomain
81{
82 struct Move
83 {
84 size_t col = 0;
85 };
86
87 using State = NQueensState;
88
89 size_t n = 0;
90
91 // A complete placement is found when all rows already contain a queen.
92 bool is_goal(const State &state) const
93 {
94 return state.row == n;
95 }
96
97 // Apply one decision: place one queen in the current row.
98 void apply(State &state, const Move &move) const
99 {
100 const size_t row = state.row;
101 const size_t down = row + state.n - 1 - move.col;
102 const size_t up = row + move.col;
103
104 state.queens[row] = static_cast<int>(move.col);
105 state.used_columns[move.col] = 1;
106 state.used_diag_down[down] = 1;
107 state.used_diag_up[up] = 1;
108 ++state.row;
109 }
110
111 // Undo exactly the last placement.
112 void undo(State &state, const Move &move) const
113 {
114 --state.row;
115 const size_t row = state.row;
116 const size_t down = row + state.n - 1 - move.col;
117 const size_t up = row + move.col;
118
119 state.queens[row] = -1;
120 state.used_columns[move.col] = 0;
121 state.used_diag_down[down] = 0;
122 state.used_diag_up[up] = 0;
123 }
124
125 // Generate safe columns for the next row without materializing child states.
126 template <typename Visitor>
127 bool for_each_successor(const State &state, Visitor visit) const
128 {
129 if (state.row >= n)
130 return true;
131
132 for (size_t col = 0; col < n; ++col)
133 {
134 const size_t down = state.row + state.n - 1 - col;
135 const size_t up = state.row + col;
136 if (state.used_columns[col] or state.used_diag_down[down] or state.used_diag_up[up])
137 continue;
138
139 if (not visit(Move{col}))
140 return false;
141 }
142
143 return true;
144 }
145};
146
147std::string signature(const NQueensState &state)
148{
149 std::string s;
150 for (size_t row = 0; row < state.n; ++row)
151 s.push_back(static_cast<char>('0' + state.queens[row]));
152 return s;
153}
154
155void print_board(const NQueensState &state)
156{
157 for (size_t row = 0; row < state.n; ++row)
158 {
159 for (size_t col = 0; col < state.n; ++col)
160 std::cout << (state.queens[row] == static_cast<int>(col) ? 'Q' : '.');
161 std::cout << '\n';
162 }
163}
164
165} // end namespace
166
167int main()
168{
169 constexpr size_t n = 4;
170
172 policy.stop_at_first_solution = false;
173
176 auto result = Search::backtracking_search(NQueensDomain{n},
177 NQueensState(n),
178 collector,
179 policy);
180
181 std::cout << "N-Queens reference example\n";
182 std::cout << "Board size: " << n << '\n';
183 std::cout << "Solutions found: " << result.stats.solutions_found << '\n';
184 std::cout << "Visited states: " << result.stats.visited_states << '\n';
185 std::cout << "Solution signatures:";
186 for (auto it = collector.solutions().get_it(); it.has_curr(); it.next_ne())
187 std::cout << ' ' << signature(it.get_curr().state);
188 std::cout << '\n';
189
190 if (result.found_solution())
191 {
192 std::cout << "First solution signature: "
193 << signature(result.best_solution.get().state) << '\n';
194 std::cout << "First solution board:\n";
195 print_board(result.best_solution.get().state);
196 }
197
198 return 0;
199}
Umbrella header for the implicit state-space search framework.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:139
Recursive depth-first backtracking over an implicit state space.
Collector that stores accepted solutions in an Aleph list.
User-facing facade exported by the umbrella search header.
size_t size(Node *root) noexcept
Divide_Conquer_DP_Result< Cost > divide_and_conquer_partition_dp(const size_t groups, const size_t n, Transition_Cost_Fn transition_cost, const Cost inf=dp_optimization_detail::default_inf< Cost >())
Optimize partition DP using divide-and-conquer optimization.
Exploration controls shared across engines.
bool stop_at_first_solution
Stop when the first goal is found.
Dynamic array container with automatic resizing.