From 3c43f7c0e6bd0013181f51abf25b1cae33b93def Mon Sep 17 00:00:00 2001 From: Himani Negi Date: Fri, 27 Dec 2019 16:57:24 +0530 Subject: [PATCH] Add backtracking/nqueen_print_all_solutions.cpp (#622) * Add files via upload * Rename Backtracking/NQueen-PrintAllSolutions.cpp to backtracking/nqueen_print_all_solutions.cpp * clang-format -i -style="{IndentWidth: 4}" *.cpp * endl --> std::endl Co-authored-by: Christian Clauss --- backtracking/nqueen_print_all_solutions.cpp | 50 +++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 backtracking/nqueen_print_all_solutions.cpp diff --git a/backtracking/nqueen_print_all_solutions.cpp b/backtracking/nqueen_print_all_solutions.cpp new file mode 100644 index 000000000..e6736da1e --- /dev/null +++ b/backtracking/nqueen_print_all_solutions.cpp @@ -0,0 +1,50 @@ +#include +#define n 4 + +void PrintSol(int Board[n][n]) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + std::cout << Board[i][j] << " "; + } + std::cout << std::endl; + } + std::cout << std::endl; +} + +bool CanIMove(int Board[n][n], int row, int col) { + /// check in the row + for (int i = 0; i < col; i++) { + if (Board[row][i] == 1) + return false; + } + /// check the first diagonal + for (int i = row, j = col; i >= 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; + } + for (int i = 0; i < n; i++) { + if (CanIMove(Board, i, col)) { + Board[i][col] = 1; + NQueenSol(Board, col + 1); + Board[i][col] = 0; + } + } +} + +int main() { + int Board[n][n] = {0}; + NQueenSol(Board, 0); +}