-
Notifications
You must be signed in to change notification settings - Fork 0
/
52nqueenII.cpp
67 lines (59 loc) · 1.1 KB
/
52nqueenII.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
56
57
58
59
60
61
62
63
64
65
66
67
//
//
//Follow up for N-Queens problem.
//
//Now, instead outputting board configurations, return the total number of distinct solutions
//
//
nt availablepos(vector<string> board, int row, int col, int n)
{
for (int i = 0; i < row; i++)
{
if (board[i][col] == 'Q')
{
return 0;
}
}
for (int i = row-1, j= col-1; i >= 0 && j>=0; i--, j--)
{
if (board[i][j] == 'Q')
{
return 0;
}
}
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++)
{
if (board[i][j] == 'Q')
{
return 0;
}
}
return 1;
}
void solveNQueens_helper(int n, vector<string> board, int&result, int row)
{
if (row == n)
{
result++;
return;
}
for (int i = 0; i < n; i++)
{
if (1 == availablepos(board, row, i, n))
{
board[row][i] = 'Q';
solveNQueens_helper(n, board, result, row + 1);
board[row][i] = '.';
}
}
}
class Solution {
public:
int totalNQueens(int n)
{
int result = 0;
vector<string>board(n, string(n, '.'));
solveNQueens_helper(n, board, result, 0);
return result;
}
};