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
25
namespace
backtracking
{
31
namespace
n_queens
{
37
template
<
size_t
n>
38
void
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
57
template
<
size_t
n>
58
bool
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
90
template
<
size_t
n>
91
void
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
120
int
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
}
backtracking::n_queens::solveNQ
void solveNQ(std::array< std::array< int, n >, n > board, const int &col)
Definition
n_queens.cpp:91
backtracking::n_queens::printSolution
void printSolution(const std::array< std::array< int, n >, n > &board)
Definition
n_queens.cpp:38
backtracking::n_queens::isSafe
bool isSafe(const std::array< std::array< int, n >, n > &board, const int &row, const int &col)
Definition
n_queens.cpp:58
main
int main()
Main function.
Definition
n_queens.cpp:120
backtracking
for vector container
n_queens
Functions for Eight Queens puzzle.
backtracking
n_queens.cpp
Generated by
1.13.2