N queens all optimized
More...
#include <array>
#include <iostream>
◆ CanIMove()
template<size_t n>
| bool backtracking::n_queens_optimized::CanIMove |
( |
const std::array< std::array< int, n >, n > & |
board, |
|
|
int |
row, |
|
|
int |
col |
|
) |
| |
Check if a queen can be placed on matrix
- Template Parameters
-
- Parameters
-
| board | matrix where numbers are saved |
| row | current index in rows |
| col | current index in columns |
- Returns
true if queen can be placed on matrix
-
false if queen can't be placed on matrix
check in the row
check the first diagonal
check the second diagonal
62 for (
int i = 0; i <= col; i++) {
63 if (board[row][i] == 1) {
68 for (
int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
69 if (board[i][j] == 1) {
74 for (
int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) {
75 if (board[i][j] == 1) {
◆ main()
Main function.
- Returns
- 0 on exit
114 for (
int i = 0; i <= n / 2 - 1; i++) {
115 if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) {
122 for (
int i = 0; i <= n / 2; i++) {
123 if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) {
◆ NQueenSol()
template<size_t n>
| void backtracking::n_queens_optimized::NQueenSol |
( |
std::array< std::array< int, n >, n > |
board, |
|
|
int |
col |
|
) |
| |
Solve n queens problem
- Template Parameters
-
- Parameters
-
| board | matrix where numbers are saved |
| col | current index in columns |
94 for (
int i = 0; i < n; i++) {
95 if (CanIMove<n>(board, i, col)) {
97 NQueenSol<n>(board, col + 1);
◆ PrintSol()
template<size_t n>
| void backtracking::n_queens_optimized::PrintSol |
( |
const std::array< std::array< int, n >, n > & |
board | ) |
|
Utility function to print matrix
- Template Parameters
-
- Parameters
-
| board | matrix where numbers are saved |
31 for (
int i = 0; i < n; i++) {
32 for (
int j = 0; j < n; j++) {
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++) {