Skip to content

Commit 65d6193

Browse files
committed
update 51. N-Queens, 52. N-Queens II
1 parent c6c64be commit 65d6193

File tree

5 files changed

+174
-46
lines changed

5 files changed

+174
-46
lines changed

Backtracking/51_NQueens.cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* @Author: [email protected]
3+
* @Last Modified time: 2016-07-18 19:42:32
4+
*/
5+
6+
class Solution {
7+
public:
8+
/*
9+
Refer to:
10+
https://discuss.leetcode.com/topic/13617/accepted-4ms-c-solution-use-backtracking-and-bitmask-easy-understand
11+
The number of columns is n, the number of 45° diagonals is 2 * n - 1,
12+
the number of 135° diagonals is also 2 * n - 1.
13+
When reach [row, col], the column No. is col,
14+
the 45° diagonal No. is row + col and the 135° diagonal No. is n - 1 + col - row.
15+
16+
| | | / / / \ \ \
17+
O O O O O O O O O
18+
| | | / / / / \ \ \ \
19+
O O O O O O O O O
20+
| | | / / / / \ \ \ \
21+
O O O O O O O O O
22+
| | | / / / \ \ \
23+
3 columns 5 45° diagonals 5 135° diagonals (when n is 3)
24+
*/
25+
vector<vector<string>> solveNQueens(int n) {
26+
vector<bool> cols(n, true);
27+
vector<bool> left_right(2*n-1, true);
28+
vector<bool> right_left(2*n-1, true);
29+
string original = string(n, '.');
30+
vector<string> queueMatrix(n, original);
31+
vector<vector<string>> ans;
32+
solve(0, queueMatrix, ans, cols, left_right, right_left, n);
33+
return ans;
34+
}
35+
36+
private:
37+
void solve(int row, vector<string> &matrix, vector<vector<string>> &ans,
38+
vector<bool> &cols, vector<bool> &left_right, vector<bool> &right_left, int n){
39+
if(row==n){
40+
// Get one Queen Square
41+
ans.push_back(matrix);
42+
return;
43+
}
44+
45+
for(int i=0; i<n; i++){
46+
if(cols[i] && left_right[n+i-row+1] && right_left[row+i]){
47+
matrix[row][i] = 'Q';
48+
cols[i] = left_right[n+i-row+1] = right_left[row+i] = false;
49+
// Solve the child question.
50+
solve(row+1, matrix, ans, cols, left_right, right_left, n);
51+
// Backtracking here.
52+
matrix[row][i] = '.';
53+
cols[i] = left_right[n+i-row+1] = right_left[row+i] = true;
54+
}
55+
}
56+
}
57+
};
58+
59+
/*
60+
1
61+
5
62+
8
63+
*/

Backtracking/51_NQueens.py

Lines changed: 34 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -6,60 +6,53 @@ class Solution(object):
66
allNQueens = []
77

88
def solveNQueens(self, n):
9-
"""
10-
:type n: int
11-
:rtype: List[List[str]]
12-
"""
139
self.allNQueens = []
14-
queueMatrix = [["." for col in range(n)] for row in range(n)]
10+
self.cols = [True] * n
11+
self.left_right = [True] * (2 * n - 1)
12+
self.right_left = [True] * (2 * n - 1)
13+
queueMatrix = [["."] * n for row in range(n)]
1514
self.solve(0, queueMatrix, n)
1615

1716
return self.allNQueens
1817

1918
def solve(self, row, matrix, n):
20-
for col in range(n):
21-
if self.isValid(row, col, matrix, n):
22-
matrix[row][col] = "Q"
19+
"""
20+
Refer to:
21+
https://discuss.leetcode.com/topic/13617/accepted-4ms-c-solution-use-backtracking-and-bitmask-easy-understand
22+
The number of columns is n, the number of 45° diagonals is 2 * n - 1,
23+
the number of 135° diagonals is also 2 * n - 1.
24+
When reach [row, col], the column No. is col,
25+
the 45° diagonal No. is row + col and the 135° diagonal No. is n - 1 + col - row.
26+
27+
| | | / / / \ \ \
28+
O O O O O O O O O
29+
| | | / / / / \ \ \ \
30+
O O O O O O O O O
31+
| | | / / / / \ \ \ \
32+
O O O O O O O O O
33+
| | | / / / \ \ \
34+
3 columns 5 45° diagonals 5 135° diagonals (when n is 3)
35+
"""
2336

24-
# Get one Queen Square
25-
if row == n - 1:
26-
result = []
27-
for i in range(n):
28-
row_str = "".join(matrix[i])
29-
result.append(row_str)
30-
self.allNQueens.append(result)
31-
matrix[row][col] = "."
32-
return
37+
# Get one Queen Square
38+
if row == n:
39+
result = ["".join(r) for r in matrix]
40+
self.allNQueens.append(result)
41+
return
3342

43+
for col in range(n):
44+
if self.cols[col] and self.left_right[row + n - 1 - col] and self.right_left[row + col]:
45+
matrix[row][col] = "Q"
46+
self.cols[col] = self.left_right[row + n - 1 - col] = self.right_left[row + col] = False
3447
# Solve the child question
3548
self.solve(row + 1, matrix, n)
49+
# Backtracking here.
3650
matrix[row][col] = "."
37-
38-
def isValid(self, row, col, matrix, n):
39-
# Check for the according col above the current row.
40-
for i in range(row):
41-
if matrix[i][col] == "Q":
42-
return False
43-
44-
# Check from left-top to right-bottom
45-
step_1 = 1
46-
while row - step_1 >= 0 and col - step_1 >= 0:
47-
if matrix[row - step_1][col - step_1] == "Q":
48-
return False
49-
step_1 += 1
50-
51-
# Check from right-top to left-bottom
52-
step_2 = 1
53-
while row - step_2 >= 0 and col + step_2 < n:
54-
if matrix[row - step_2][col + step_2] == "Q":
55-
return False
56-
step_2 += 1
57-
58-
return True
51+
self.cols[col] = self.left_right[
52+
row + n - 1 - col] = self.right_left[row + col] = True
5953

6054
"""
61-
0
6255
1
6356
5
64-
57+
8
6558
"""

Backtracking/52_NQueensII.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* @Author: [email protected]
3+
* @Last Modified time: 2016-07-18 16:31:27
4+
*/
5+
6+
class Solution {
7+
public:
8+
int totalNQueens(int n) {
9+
vector<bool> cols(n, true);
10+
vector<bool> left_right(2*n-1, true);
11+
vector<bool> right_left(2*n-1, true);
12+
int count = 0;
13+
solveNQueens(0, cols, left_right, right_left, count);
14+
return count;
15+
}
16+
private:
17+
/*
18+
Refer to:
19+
https://discuss.leetcode.com/topic/13617/accepted-4ms-c-solution-use-backtracking-and-bitmask-easy-understand
20+
The number of columns is n, the number of 45° diagonals is 2 * n - 1,
21+
the number of 135° diagonals is also 2 * n - 1.
22+
When reach [row, col], the column No. is col,
23+
the 45° diagonal No. is row + col and the 135° diagonal No. is n - 1 + col - row.
24+
25+
| | | / / / \ \ \
26+
O O O O O O O O O
27+
| | | / / / / \ \ \ \
28+
O O O O O O O O O
29+
| | | / / / / \ \ \ \
30+
O O O O O O O O O
31+
| | | / / / \ \ \
32+
3 columns 5 45° diagonals 5 135° diagonals (when n is 3)
33+
*/
34+
void solveNQueens(int row, vector<bool> &cols, vector<bool> &lr, vector<bool> &rl, int &count){
35+
if(row==cols.size()){
36+
count ++;
37+
return;
38+
}
39+
for(int i=0; i<cols.size(); i++){
40+
if(cols[i] && lr[row+cols.size()-1-i] && rl[row+i]){
41+
cols[i] = lr[row+cols.size()-1-i] = rl[row+i] = false;
42+
solveNQueens(row+1, cols, lr, rl, count);
43+
cols[i] = lr[row+cols.size()-1-i] = rl[row+i] = true;
44+
}
45+
}
46+
}
47+
};
48+
49+
/*
50+
1
51+
2
52+
8
53+
*/

Week07/52.py renamed to Backtracking/52_NQueensII.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,24 @@ def solveNQueens(self, row, cols_used, n):
2323
cols_used[row] = -1
2424

2525
def isValid(self, row, col, cols_used, n):
26+
""" Can check isvalid with using hash, implemented by c++.
27+
28+
Refer to:
29+
https://discuss.leetcode.com/topic/13617/accepted-4ms-c-solution-use-backtracking-and-bitmask-easy-understand
30+
The number of columns is n, the number of 45° diagonals is 2 * n - 1,
31+
the number of 135° diagonals is also 2 * n - 1.
32+
When reach [row, col], the column No. is col,
33+
the 45° diagonal No. is row + col and the 135° diagonal No. is n - 1 + col - row.
34+
35+
| | | / / / \ \ \
36+
O O O O O O O O O
37+
| | | / / / / \ \ \ \
38+
O O O O O O O O O
39+
| | | / / / / \ \ \ \
40+
O O O O O O O O O
41+
| | | / / / \ \ \
42+
3 columns 5 45° diagonals 5 135° diagonals (when n is 3)
43+
"""
2644
for i in range(row):
2745
# Check for the according col above the current row.
2846
if cols_used[i] == col:
@@ -38,7 +56,7 @@ def isValid(self, row, col, cols_used, n):
3856
return True
3957

4058
"""
41-
if __name__ == '__main__':
42-
sol = Solution()
43-
print sol.totalNQueens(8)
59+
1
60+
5
61+
8
4462
"""

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
12
# [Array](Array/)
23

34
* 026. [Remove Duplicates from Sorted Array](Array/26_RemoveDuplicatesFromSortedArray.py)
@@ -157,8 +158,8 @@
157158
* 039. [Combination Sum](Backtracking/39_CombinationSum.py)
158159
* 046. [Permutations](Backtracking/46_Permutations.py)
159160
* 047. [Permutations II](Backtracking/47_PermutationsII.py)
160-
* 051. N-Queens
161-
* 052. N-Queens II
161+
* 051. [N-Queens](Backtracking/51_NQueens.py)
162+
* 052. [N-Queens II](Backtracking/52_NQueensII.py)
162163
* 079. [Word Search](Backtracking/79_WordSearch.py)
163164
* 090. [Subsets II](Backtracking/90_SubsetsII.py)
164165
* 093. [Restore IP Addresses](Backtracking/93_RestoreIPAddresses.py)

0 commit comments

Comments
 (0)