From a83e44ea6c6b5c2e979ffcb9b4c1c8aa2a942c55 Mon Sep 17 00:00:00 2001 From: Sombit Bose Date: Wed, 29 Apr 2020 22:11:47 +0530 Subject: [PATCH] Create n_queens_all_solution_optimised.cpp --- .../n_queens_all_solution_optimised.cpp | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 backtracking/n_queens_all_solution_optimised.cpp diff --git a/backtracking/n_queens_all_solution_optimised.cpp b/backtracking/n_queens_all_solution_optimised.cpp new file mode 100644 index 000000000..f8da31c4f --- /dev/null +++ b/backtracking/n_queens_all_solution_optimised.cpp @@ -0,0 +1,86 @@ +#include +#define n 4 +#define inc_loop(var,start,stop,step) for(int var=start;var<=stop;var+=step) +#define dec_loop(var,start,stop,step) for(int var=start;var>=stop;var-=step) + +void PrintSol(int Board[n][n]) +{ + inc_loop(i,0,n-1,1) + { + inc_loop(j,0,n-1,1) + std::cout << Board[i][j] << " "; + std::cout << std::endl; + } + std::cout << std::endl; + if (n%2==0 || (n%2==1 && Board[n/2+1][0]!=1)) + { + inc_loop(i,0,n-1,1) + { + dec_loop(j,n-1,0,1) + std::cout<= 0 && j >= 0; i--, j--) { + if (Board[i][j] == 1) + return false; + } + /// check the second diagonal + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { + if (Board[i][j] == 1) + return false; + } + return true; +} + +void NQueenSol(int Board[n][n], int col) { + if (col >= n) { + PrintSol(Board); + return; + } + inc_loop(i,0,n-1,1) + { + if (CanIMove(Board, i, col)) { + Board[i][col] = 1; + NQueenSol(Board, col + 1); + Board[i][col] = 0; + } + } +} + +int main() { + int Board[n][n] = {0}; + if (n%2==0) + { + inc_loop(i,0,n/2-1,1) + { + if (CanIMove(Board, i, 0)) { + Board[i][0] = 1; + NQueenSol(Board,1); + Board[i][0] = 0; + } + } + } + else + { + inc_loop(i,0,n/2,1) + { + if (CanIMove(Board, i,0)) { + Board[i][0] = 1; + NQueenSol(Board,1); + Board[i][0] = 0; + } + } + } + return 0; +}