-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathN-QueenProblem.cpp
More file actions
83 lines (66 loc) · 1.53 KB
/
Copy pathN-QueenProblem.cpp
File metadata and controls
83 lines (66 loc) · 1.53 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Queen {
public:
bool valid(int row, int col, vector<string>arr){
int n = arr.size();
// check row
for(int i = 0; i < n; i++){
if(arr[row][i] != '.'){
return 0;
}
}
// check column
for(int i = 0; i < n; i++){
if(arr[i][col] != '.'){
return 0;
}
}
// check diagonal (upper left to lower right)
int i = row, j = col;
while(i >= 0 && j >= 0){
if(arr[i][j] != '.'){
return 0;
}
i--;
j--;
}
// check diagonal (lower left to upper right)
i = row, j = col;
while(i >= 0 && j < n){
if(arr[i][j] != '.'){
return 0;
}
i--;
j++;
}
return 1;
}
void dfs(int index, int count, int n, vector<string> arr, vector<vector<string>> &ans ){
if(count == n){
ans.push_back(arr);
return;
}
if(index >= n){
return;
}
for(int i=0; i<n; i++){
if(valid(index, i, arr)){
arr[index][i] = 'Q';
dfs(index + 1, count + 1, n, arr, ans);
arr[index][i] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<string> arr;
string brr;
vector<vector<string>> ans;
for(int i = 0; i < n; i++){
brr += '.';
}
for(int i = 0; i < n; i++ ){
arr.push_back(brr);
}
dfs(0, 0, n, arr, ans);
return ans;
}
};