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; + + } + +};