Skip to content

Commit a3e1047

Browse files
Create nqueens.cpp
1 parent c68d522 commit a3e1047

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

nqueens.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
class Solution {
2+
public:
3+
vector<vector<string>>global_result;
4+
5+
void printResult(int matrix[][9],int n){
6+
vector<string> local_result(n);
7+
for(int i=0;i<n;i++) {
8+
string tmp=""; // creating a tmp string
9+
for(int j=0;j<n;j++) {
10+
if(matrix[i][j]==1) {
11+
tmp+="Q"; // appending the results to the tmp string
12+
} else {
13+
tmp+=".";
14+
}
15+
}
16+
local_result[i]=tmp; // putting the final tmp string result into the vector
17+
}
18+
global_result.push_back(local_result); // inserting the final vector into the resultatnt vector
19+
}
20+
21+
bool isValid(int matrix[][9],int row,int col,int n) {
22+
23+
// col check
24+
for(int r=0;r<row;r++) {
25+
if(matrix[r][col]==1) return false;
26+
}
27+
28+
// left diagonal
29+
int i=row,j=col;
30+
while(i>=0 && j>=0) {
31+
if(matrix[i][j]==1) return false;
32+
i--;j--;
33+
}
34+
35+
// right diagonal
36+
i=row,j=col;
37+
while(i>=0 && j<n) {
38+
if(matrix[i][j]==1) return false;
39+
i--;j++;
40+
}
41+
42+
return true;
43+
}
44+
45+
bool solve(int matrix[][9],int row,int n){
46+
if(row==n) { // if in all the rows, queens are placed, that means we have reached the end, print the Chessboard
47+
printResult(matrix,n);
48+
return true;
49+
}
50+
bool nextQueen=false; // "assuming that next Queen's placement is not decided YET"
51+
for(int col=0;col<n;col++) { // moving into all the columns of "row" (look at the solve() func call above)
52+
if(isValid(matrix,row,col,n)) { // Checking if we can place the queen at this particularr place
53+
matrix[row][col]=1; // if yes, mark it as 1
54+
nextQueen = solve(matrix,row+1,n);// now looking for next Queen's placement, moving to the next row and calling this function Recursively.
55+
matrix[row][col]=0; //Backtracking
56+
}
57+
}
58+
return nextQueen; // returning the nextQueen's placement decision's to the function that called it RECURSIVELY
59+
}
60+
vector<vector<string>> solveNQueens(int n) {
61+
int matrix[9][9]={0}; // creating an 2d array of 9X9 since that os the max limit
62+
solve(matrix,0,n); // solve(matrix,starting row,max rows)
63+
return global_result;
64+
65+
}
66+
};

0 commit comments

Comments
 (0)