Skip to content

Commit 7a0f272

Browse files
author
Sahil
authored
Merge pull request royalpranjal#30 from khannagautam/patch-3
Added solution for N Queens
2 parents 14d700b + 5c9623f commit 7a0f272

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Backtracking/N Queens

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
vector<vector<string> >ans;
2+
int n;
3+
4+
void recur(int ind, vector<int> pos)
5+
{
6+
int i,j;
7+
if(ind == n)
8+
{
9+
vector<string> valid;
10+
for(i=0;i<n;i++)
11+
{
12+
string row = "";
13+
for(j=0;j<n;j++)
14+
{
15+
if(j == pos[i])
16+
row += 'Q';
17+
else
18+
row += '.';
19+
}
20+
valid.push_back(row);
21+
}
22+
ans.push_back(valid);
23+
24+
return;
25+
}
26+
for(i = 0;i<n;i++)
27+
{
28+
bool flag = true;
29+
for(j=0;j<pos.size();j++)
30+
{
31+
if(abs(ind-j) == abs(pos[j]-i) || i == pos[j])
32+
flag = false;
33+
}
34+
if(!flag)
35+
continue;
36+
pos.push_back(i);
37+
recur(ind+1,pos);
38+
pos.pop_back();
39+
//pos[ind] = -1;
40+
}
41+
}
42+
vector<vector<string> > Solution::solveNQueens(int A)
43+
{
44+
ans.clear();
45+
vector<int> pos;
46+
int i;
47+
n = A;
48+
recur(0,pos);
49+
return ans;
50+
}

0 commit comments

Comments
 (0)