From fbeb3c3124dc6d108910b7588fce7b484fc5f2df Mon Sep 17 00:00:00 2001 From: Soumyajit Sen <66264486+soumyajit1999@users.noreply.github.com> Date: Sun, 10 Oct 2021 17:14:51 +0530 Subject: [PATCH] Create N-Queens.cpp --- N-Queens.cpp | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 N-Queens.cpp diff --git a/N-Queens.cpp b/N-Queens.cpp new file mode 100644 index 00000000..6679cae2 --- /dev/null +++ b/N-Queens.cpp @@ -0,0 +1,79 @@ +#define N 4 +#include +#include +void printSolution(int board[N][N]) +{ + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + printf(" %d ", board[i][j]); + printf("\n"); + } +} +bool isSafe(int board[N][N], int row, int col) +{ + int i, j; + for (i = 0; i < col; i++) + if (board[row][i]) + return false; + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) + if (board[i][j]) + return false; + for (i = row, j = col; j >= 0 && i < N; i++, j--) + if (board[i][j]) + return false; + + return true; +} +bool solveNQUtil(int board[N][N], int col) +{ + /* base case: If all queens are placed + then return true */ + if (col >= N) + return true; + + /* Consider this column and try placing + this queen in all rows one by one */ + for (int i = 0; i < N; i++) { + /* Check if the queen can be placed on + board[i][col] */ + if (isSafe(board, i, col)) { + /* Place this queen in board[i][col] */ + board[i][col] = 1; + + /* recur to place rest of the queens */ + if (solveNQUtil(board, col + 1)) + return true; + + /* If placing queen in board[i][col] + doesn't lead to a solution, then + remove queen from board[i][col] */ + board[i][col] = 0; // BACKTRACK + } + } + + /* If the queen cannot be placed in any row in + this colum col then return false */ + return false; +} + +bool solveNQ() +{ + int board[N][N] = { { 0, 0, 0, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 0, 0 } }; + + if (solveNQUtil(board, 0) == false) { + printf("Solution does not exist"); + return false; + } + + printSolution(board); + return true; +} + +int main() +{ + solveNQ(); + return 0; +}