TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
n_queens.cpp
Go to the documentation of this file.
1
18#include <array>
19#include <iostream>
20
25namespace backtracking {
31namespace n_queens {
37template <size_t n>
38void printSolution(const std::array<std::array<int, n>, n> &board) {
39 std::cout << "\n";
40 for (int i = 0; i < n; i++) {
41 for (int j = 0; j < n; j++) {
42 std::cout << "" << board[i][j] << " ";
43 }
44 std::cout << "\n";
45 }
46}
47
57template <size_t n>
58bool isSafe(const std::array<std::array<int, n>, n> &board, const int &row,
59 const int &col) {
60 int i = 0, j = 0;
61
62 // Check this row on left side
63 for (i = 0; i < col; i++) {
64 if (board[row][i]) {
65 return false;
66 }
67 }
68
69 // Check upper diagonal on left side
70 for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
71 if (board[i][j]) {
72 return false;
73 }
74 }
75 // Check lower diagonal on left side
76 for (i = row, j = col; j >= 0 && i < n; i++, j--) {
77 if (board[i][j]) {
78 return false;
79 }
80 }
81 return true;
82}
83
90template <size_t n>
91void solveNQ(std::array<std::array<int, n>, n> board, const int &col) {
92 if (col >= n) {
93 printSolution<n>(board);
94 return;
95 }
96
97 // Consider this column and try placing
98 // this queen in all rows one by one
99 for (int i = 0; i < n; i++) {
100 // Check if queen can be placed
101 // on board[i][col]
102 if (isSafe<n>(board, i, col)) {
103 // Place this queen in matrix
104 board[i][col] = 1;
105
106 // Recursive to place rest of the queens
107 solveNQ<n>(board, col + 1);
108
109 board[i][col] = 0; // backtrack
110 }
111 }
112}
113} // namespace n_queens
114} // namespace backtracking
115
120int main() {
121 const int n = 4;
122 std::array<std::array<int, n>, n> board = {
123 std::array<int, n>({0, 0, 0, 0}), std::array<int, n>({0, 0, 0, 0}),
124 std::array<int, n>({0, 0, 0, 0}), std::array<int, n>({0, 0, 0, 0})};
125
126 backtracking::n_queens::solveNQ<n>(board, 0);
127 return 0;
128}
void solveNQ(std::array< std::array< int, n >, n > board, const int &col)
Definition n_queens.cpp:91
int main()
Main function.
Definition n_queens.cpp:120
for vector container
Functions for Eight Queens puzzle.