-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNqueens.cpp
More file actions
72 lines (69 loc) · 1.77 KB
/
Nqueens.cpp
File metadata and controls
72 lines (69 loc) · 1.77 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
vector<string> intToQ(vector<vector<int>> &board, int n){
vector<string> tmp(n);
for(int i=0;i<n;i++)
tmp[i] = ".";
vector<string> res;
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if (board[i][j]!=0){
tmp[j] = 'Q';
break;
}
}
string t = "";
for(auto x:tmp)
t.append(x);
res.push_back(t);
tmp[j] = ".";
}
return res;
}
bool isSafe(vector<vector<int>> &board, int row, int col, int n){
for(int j=0;j<col;j++)
if (board[row][j]!=0)
return false;
int i=row;
int j = col;
while (i>=0 && j>=0){
if (board[i][j]!=0)
return false;
i--;
j--;
}
i = row;
j = col;
while (i<n && j>=0){
if(board[i][j]!=0)
return false;
i++;
j--;
}
return true;
}
bool solveQ(vector<vector<string>> &res, vector<vector<int>> &board, int col, int n){
if (col==n){
vector<string> tmp = intToQ(board,n);
res.push_back(tmp);
return true;
}
bool r = false;
for(int i=0;i<n;i++){
if (isSafe(board,i,col,n)){
board[i][col] = 1;
r = (solveQ(res,board,col+1,n) || r);
board[i][col] = 0;
}
}
return r;
}
vector<vector<string> > Solution::solveNQueens(int A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
vector<vector<int>> board(A,vector<int>(A,0));
vector<vector<string>> res;
bool tmp = solveQ(res,board,0,A);
return res;
}