From 7cd2b2dc086e038c966950a39f65d11722d560fb Mon Sep 17 00:00:00 2001 From: Natwar Gopal Date: Wed, 19 Oct 2022 20:57:44 +0530 Subject: [PATCH] Added N_Queens --- Backtracking/N-Queens.cpp | 104 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 Backtracking/N-Queens.cpp diff --git a/Backtracking/N-Queens.cpp b/Backtracking/N-Queens.cpp new file mode 100644 index 0000000..686834c --- /dev/null +++ b/Backtracking/N-Queens.cpp @@ -0,0 +1,104 @@ +/* +https://leetcode.com/problems/n-queens/description/ +51. N-Queens +Leetcode Hard +*/ +class Solution { + + bool isPossible(vector& partialAns, int row, int col, int n) { + + + int len = partialAns.size(); + + for(int i = 0;i=0 and j=0 and j>=0) { + + if(partialAns[i][j]=='Q') return 0; + + i--;j--; + + } + + + + return 1; + + } + + void helper(vector>& ans, int n, int row, vector& partialAns) { + + + + if(row >= n) { + + ans.push_back(partialAns); + + return; + + } + + string s = ""; + + for(int col=0;col < n;col++) { + + if(isPossible(partialAns,row,col,n)) { + + string temp = s; + + temp+='Q'; + + int i = col; + + while(i> solveNQueens(int n) { + + vector> ans; + + vector partialAns; + + helper(ans,n,0,partialAns); + + return ans; + + } + +};