forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path051.N-Queens.cpp
51 lines (48 loc) · 1.19 KB
/
051.N-Queens.cpp
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
class Solution {
public:
vector<vector<string>> solveNQueens(int n)
{
vector<vector<string>>results;
vector<int>Qpos(n,-1);
DFS(0,results,Qpos);
return results;
}
void DFS(int row, vector<vector<string>>&results, vector<int>&Qpos)
{
int n = Qpos.size();
if (row==n)
{
vector<string> board;
for (int i=0; i<n; i++)
{
string temp;
for (int j=0; j<n; j++)
temp+='.';
temp[Qpos[i]]='Q';
board.push_back(temp);
}
results.push_back(board);
}
else
{
for (int col=0; col<n; col++)
{
if (isValid(Qpos,row,col))
{
Qpos[row]=col;
DFS(row+1,results,Qpos);
Qpos[row]=-1;
}
}
}
}
bool isValid(vector<int>Qpos, int row, int col)
{
for (int i=0; i<row; i++)
{
if (Qpos[i]==col || abs(i-row)==abs(Qpos[i]-col))
return false;
}
return true;
}
};