Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added N_Queens #131

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Added N_Queens
  • Loading branch information
natwargopal committed Oct 19, 2022
commit 7cd2b2dc086e038c966950a39f65d11722d560fb
104 changes: 104 additions & 0 deletions Backtracking/N-Queens.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
https://leetcode.com/problems/n-queens/description/
51. N-Queens
Leetcode Hard
*/
class Solution {

bool isPossible(vector<string>& partialAns, int row, int col, int n) {


int len = partialAns.size();

for(int i = 0;i<len;i++) {

if(partialAns[i][col] == 'Q') return 0;

}

int i=row-1, j = col + 1;

while(i>=0 and j<n) {

if(partialAns[i][j]=='Q') return 0;

i--;j++;

}

i=row - 1, j = col -1;

while(i>=0 and j>=0) {

if(partialAns[i][j]=='Q') return 0;

i--;j--;

}



return 1;

}

void helper(vector<vector<string>>& ans, int n, int row, vector<string>& 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<n-1){

temp+='.';

i++;

}
partialAns.push_back(temp);

helper(ans,n,row+1,partialAns);

partialAns.pop_back();

}

s+=".";

}

}

public:

vector<vector<string>> solveNQueens(int n) {

vector<vector<string>> ans;

vector<string> partialAns;

helper(ans,n,0,partialAns);

return ans;

}

};