forked from leetcoders/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-QueensII.h
129 lines (120 loc) · 3.14 KB
/
N-QueensII.h
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
Author: Annie Kim, [email protected]
Date: Apr 24, 2013
Update: Aug 23, 2013
Problem: N-Queens II
Difficulty: Medium
Source: http://leetcode.com/onlinejudge#question_52
Notes:
The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other.
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.."]
]
Solution: 1. Recursion.
2. Recursion + bit version. (fast)
The idea is from http://www.matrix67.com/blog/archives/266 (in chinese).
3. Iteration.
*/
class Solution {
public:
int totalNQueens(int n) {
return totalNQueens_2(n);
}
// solution 1: recursion
int totalNQueens_1(int n)
{
int board[n];
memset(board, -1, sizeof(board));
int res = 0;
totalNQueensRe(n, 0, board, res);
return res;
}
void totalNQueensRe(int n, int row, int board[], int &res)
{
if (row == n)
{
res++;
return;
}
for (int i = 0; i < n; ++i)
{
if (isValid(board, row, i))
{
board[row] = i;
totalNQueensRe(n, row + 1, board, res);
board[row] = -1;
}
}
}
bool isValid(int board[], int row, int col)
{
for (int i = 0; i < row; ++i)
if (board[i] == col || row - i == abs(col - board[i]))
return false;
return true;
}
// solution 2: bit version
int totalNQueens_2(int n) {
int res = 0;
totalNQueensRe_2(n, 0, 0, 0, res);
return res;
}
void totalNQueensRe_2(int n, int row, int ld, int rd, int &res)
{
if (row == (1 << n) - 1)
{
res++;
return;
}
int avail = ~(row | ld | rd);
for (int i = n - 1; i >= 0; --i)
{
int pos = 1 << i;
if (avail & pos)
totalNQueensRe_2(n, row | pos, (ld | pos) << 1, (rd | pos) >> 1, res);
}
}
// solution 3: iterative solution
int totalNQueens_3(int n)
{
int board[n];
memset(board, -1, sizeof(board));
int row = 0;
int res = 0;
while (row != -1)
{
if (row == n)
{
res++;
row--;
}
int i = board[row] == -1 ? 0 : board[row] + 1;
for (; i < n; ++i)
{
if (isValid(board, row, i))
{
board[row] = i;
row++;
break;
}
}
if (i == n)
{
board[row] = -1;
row--;
}
}
return res;
}
};