From a44b85bd4deca4177998765cc555ffa4c67338d4 Mon Sep 17 00:00:00 2001 From: Bhav Khurana <96694482+bhav-khurana@users.noreply.github.com> Date: Mon, 30 May 2022 23:15:35 +0530 Subject: [PATCH] Add N Queen problem algorithm file --- c++/nqueen.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 c++/nqueen.cpp diff --git a/c++/nqueen.cpp b/c++/nqueen.cpp new file mode 100644 index 0000000..997586e --- /dev/null +++ b/c++/nqueen.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; +int n; + +bool safe(vector> &board, int r, int c) { + for (int i = 0; i < c; i++) if (board[r][i] == 1) return false; + for (int i = r, j = c; i >= 0 && j >= 0; i--,j--) if (board[i][j] == 1) return false; + for (int i = r, j = c; i < n && j >= 0; i++,j--) if (board[i][j] == 1) return false; + return true; +} + +bool solve(vector> &board, int c) { + if (c >= n) return true; + else { + for (int i = 0; i < n; i++) + { + if (safe(board, i,c)) { + board[i][c] = 1; + if (solve(board, c+1)) return true; + board[i][c] = 0; + } + } + return false; + } +} + +signed main() +{ + cout << "Enter the value of N\n"; + cin >> n; + vector> board(100, vector (100, 0)); + if (!solve(board, 0)) cout << "No Solution exists!\n"; + else { + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cout << board[i][j] << " "; + } + cout << endl; + } + + } + return 0; +} \ No newline at end of file