TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
nqueen_print_all_solutions.cpp
Go to the documentation of this file.
1
10
#include <array>
11
#include <iostream>
12
17
namespace
backtracking
{
24
namespace
n_queens_all_solutions
{
30
template
<
size_t
n>
31
void
PrintSol
(
const
std::array<std::array<int, n>, n>& board) {
32
for
(
int
i = 0; i < n; i++) {
33
for
(
int
j = 0; j < n; j++) {
34
std::cout << board[i][j] <<
" "
;
35
}
36
std::cout << std::endl;
37
}
38
std::cout << std::endl;
39
}
40
50
template
<
size_t
n>
51
bool
CanIMove
(
const
std::array<std::array<int, n>, n>& board,
int
row,
52
int
col) {
54
for
(
int
i = 0; i < col; i++) {
55
if
(board[row][i] == 1) {
56
return
false
;
57
}
58
}
60
for
(
int
i = row, j = col; i >= 0 && j >= 0; i--, j--) {
61
if
(board[i][j] == 1) {
62
return
false
;
63
}
64
}
66
for
(
int
i = row, j = col; i <= n - 1 && j >= 0; i++, j--) {
67
if
(board[i][j] == 1) {
68
return
false
;
69
}
70
}
71
return
true
;
72
}
73
80
template
<
size_t
n>
81
void
NQueenSol
(std::array<std::array<int, n>, n> board,
int
col) {
82
if
(col >= n) {
83
PrintSol
(board);
84
return
;
85
}
86
for
(
int
i = 0; i < n; i++) {
87
if
(
CanIMove
(board, i, col)) {
88
board[i][col] = 1;
89
NQueenSol
(board, col + 1);
90
board[i][col] = 0;
91
}
92
}
93
}
94
}
// namespace n_queens_all_solutions
95
}
// namespace backtracking
96
101
int
main
() {
102
const
int
n = 4;
103
std::array<std::array<int, n>, n> board{0};
104
105
backtracking::n_queens_all_solutions::NQueenSol
(board, 0);
106
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
backtracking
for vector container
n_queens_all_solutions
Functions for the Eight Queens puzzle with all solutions.
backtracking::n_queens_all_solutions::NQueenSol
void NQueenSol(std::array< std::array< int, n >, n > board, int col)
Main function to solve the N Queens problem.
Definition
nqueen_print_all_solutions.cpp:81
backtracking::n_queens_all_solutions::CanIMove
bool CanIMove(const std::array< std::array< int, n >, n > &board, int row, int col)
Check if a queen can be placed on the matrix.
Definition
nqueen_print_all_solutions.cpp:51
backtracking::n_queens_all_solutions::PrintSol
void PrintSol(const std::array< std::array< int, n >, n > &board)
Utility function to print matrix.
Definition
nqueen_print_all_solutions.cpp:31
backtracking
nqueen_print_all_solutions.cpp
Generated by
1.18.0