Leetcode (Hard) : N-Queens II #52
Title: Understanding the N-Queens Problem: Logic, Implementation, and Insights
Introduction:
Logic Behind the Solution:
Implementation Overview:
Recommended by LinkedIn
Key Components of the Implementation:
Intuition Behind the Approach:
Insights from the Code:
Conclusion:
class Solution {
private:
int count = 0;
void board( vector<vector<bool>>& chess,int row ,int Q )
{
if(Q==0){
count++;
return ;
}
for(int c = 0;c<chess.size();c++){
if(issafe(chess,row,c,chess.size())){
chess[row][c] = true;
board(chess,row+1,Q-1);
chess[row][c]=false ;
}
}
}
bool issafe(vector<vector<bool>>& chess,int r,int c,int n){
// upward check
for(int row = r-1;row>=0;row--){
if(chess[row][c]){
return false ;
}
}
//left upward check
int drow = r;
int dcol = c;
while(drow>=0 && dcol>=0){
if(chess[drow][dcol]){
return false ;
}
drow--;
dcol--;
}
//right upward check
int rdrow = r;
int ldcol = c;
while(rdrow>=0&&ldcol<n){
if(chess[rdrow][ldcol]){
return false ;
}
rdrow--;
ldcol ++;
}
return true ;
}
public:
int totalNQueens(int n) {
vector<vector<bool>> chess(n, vector<bool>(n, false));;
board(chess,0,n);
return count;
}
};