forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbacktracking n queen problem
53 lines (51 loc) · 1.21 KB
/
backtracking n queen problem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
bool isSafe(int n,int r,int c,vector<int>upper_left_diag,vector<int>upper_right_diag,vector<int>upper_st){
if(upper_left_diag[n-1-r+c]==1){
return false;
}
else if(upper_right_diag[r+c]==1){
return false;
}
else if(upper_st[c]==1){
return false;
}
return true;
}
void helper(int n,int row,vector<string>chess,vector<vector<string>>&ans,vector<int>upper_left_diag,vector<int>upper_right_diag,vector<int>upper_st){
if(row==n){
ans.push_back(chess);
return;
}
else{
for(int i=0;i<n;i++){
bool is_safe=isSafe(n,row,i,upper_left_diag,upper_right_diag,upper_st);
if(is_safe){
chess[row][i]='Q';
upper_left_diag[n-1-row+i]=1;
upper_right_diag[row+i]=1;
upper_st[i]=1;
helper(n,row+1,chess,ans,upper_left_diag,upper_right_diag,upper_st);
chess[row][i]='.';
upper_left_diag[n-1-row+i]=0;
upper_right_diag[row+i]=0;
upper_st[i]=0;
}
}
return;
}
}
vector<vector<string>> solveNQueens(int n) {
vector<string>chess(n);
string s(n,'.');
for(int i=0;i<n;i++){
chess[i]=s;
}
vector<vector<string>>ans;
vector<int>upper_left_diag(2*n,0);
vector<int>upper_right_diag(2*n,0);
vector<int>upper_st(n,0);
helper(n,0,chess,ans,upper_left_diag,upper_right_diag,upper_st);
return ans;
}
};