forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.cpp
55 lines (50 loc) · 1.17 KB
/
solution.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
52
53
54
55
class Solution
{
public:
vector<vector<string> > result;
vector<string> tempResult;
vector<int> chessBoard;
int target;
bool isAvailable(int row, int line)
{
for(int i=0;i<row;i++)
{
if( line == chessBoard[i]
|| abs(row-i) == abs(line - chessBoard[i]) )
return false;
}
return true;
}
void solve(int curLine)
{
if(curLine == target)
{
result.push_back(tempResult);
for(int i=0;i<target;i++)
result.back()[i][chessBoard[i]] = 'Q';
}
else
{
for(int i=0;i<target;i++)
{
if(isAvailable(curLine,i))
{
chessBoard[curLine] = i;
solve(curLine+1);
}
}
}
}
vector<vector<string> > solveNQueens(int n)
{
chessBoard.resize(n);
target = n;
string tempRow;
for(int i=0;i<n;i++)
tempRow.push_back('.');
for(int i=0;i<n;i++)
tempResult.push_back(tempRow);
solve(0);
return result;
}
};