TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
n_queens_all_solution_optimised.cpp
Go to the documentation of this file.
1
10#include <array>
11#include <iostream>
12
17namespace backtracking {
23namespace n_queens_optimized {
29template <size_t n>
30void PrintSol(const std::array<std::array<int, n>, n> &board) {
31 for (int i = 0; i < n; i++) {
32 for (int j = 0; j < n; j++) {
33 std::cout << board[i][j] << " ";
34 }
35 std::cout << std::endl;
36 }
37 std::cout << std::endl;
38 if (n % 2 == 0 || (n % 2 == 1 && board[n / 2 + 1][0] != 1)) {
39 for (int i = 0; i < n; i++) {
40 for (int j = 0; j < n; j++) {
41 std::cout << board[j][i] << " ";
42 }
43 std::cout << std::endl;
44 }
45 std::cout << std::endl;
46 }
47}
48
58template <size_t n>
59bool CanIMove(const std::array<std::array<int, n>, n> &board, int row,
60 int col) {
62 for (int i = 0; i <= col; i++) {
63 if (board[row][i] == 1) {
64 return false;
65 }
66 }
68 for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
69 if (board[i][j] == 1) {
70 return false;
71 }
72 }
74 for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) {
75 if (board[i][j] == 1) {
76 return false;
77 }
78 }
79 return true;
80}
81
88template <size_t n>
89void NQueenSol(std::array<std::array<int, n>, n> board, int col) {
90 if (col >= n) {
91 PrintSol<n>(board);
92 return;
93 }
94 for (int i = 0; i < n; i++) {
95 if (CanIMove<n>(board, i, col)) {
96 board[i][col] = 1;
97 NQueenSol<n>(board, col + 1);
98 board[i][col] = 0;
99 }
100 }
101}
102} // namespace n_queens_optimized
103} // namespace backtracking
104
109int main() {
110 const int n = 4;
111 std::array<std::array<int, n>, n> board{};
112
113 if (n % 2 == 0) {
114 for (int i = 0; i <= n / 2 - 1; i++) {
115 if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) {
116 board[i][0] = 1;
117 backtracking::n_queens_optimized::NQueenSol(board, 1);
118 board[i][0] = 0;
119 }
120 }
121 } else {
122 for (int i = 0; i <= n / 2; i++) {
123 if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) {
124 board[i][0] = 1;
125 backtracking::n_queens_optimized::NQueenSol(board, 1);
126 board[i][0] = 0;
127 }
128 }
129 }
130 return 0;
131}
void PrintSol(const std::array< std::array< int, n >, n > &board)
void NQueenSol(std::array< std::array< int, n >, n > board, int col)
bool CanIMove(const std::array< std::array< int, n >, n > &board, int row, int col)
int main()
Main function.
for vector container
Functions for Eight Queens puzzle optimized.