forked from dreamerHarshit/Coding_Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN_Queen.cpp
More file actions
73 lines (68 loc) · 1.77 KB
/
N_Queen.cpp
File metadata and controls
73 lines (68 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
73
/*
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. N Queens: Example 1 Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. For example, There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
*/
bool IsSafe(vector<string> &r, int curr_row, int col, int A){
int row=curr_row, c=col;
while(row-1>=0 && c-1>=0){
if(r[row-1][c-1]=='Q'){
return false;
}
else{
row--;
c--;
}
}
row=curr_row, c=col;
while(row-1>=0){
if(r[row-1][c]=='Q'){
return false;
}
else{
row--;
}
}
row=curr_row, c=col;
while(row-1>=0 && c+1<=A){
if(r[row-1][c+1]=='Q'){
return false;
}
else{
row--;
c++;
}
}
return true;
}
/*Recurssive Funstion*/
void count_nqueen(int curr_row, vector<string> &r, int &A, vector<vector<string>> &result){
if(curr_row>=A)
{
result.push_back(r);
return;
}
for(int i=0;i<A;i++){
if(IsSafe(r,curr_row,i, A)){
r[curr_row][i]='Q';
count_nqueen(curr_row+1, r, A, result);
r[curr_row][i]='.';
}
}
}
/* Main Function */
vector<vector<string> > Solution::solveNQueens(int A) {
int curr_row=0;
vector<string> m(A,string(A,'.'));
vector<vector<string>> result;
count_nqueen(curr_row, m, A, result);
return result;
}