简繁EN

LeetCodeNo. 123

[LeetCode with Python] 52. N-Queens II

Contents

Problem

Problem page: https://leetcode.com/problems/n-queens-ii/
Topics: Backtracking
Difficulty: Hard
Similar problems: (H) N-Queens

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

8-queens


Analysis

I use backtracking, just like in the previous problem, N-Queens. I work row by row, trying every column for each queen. The list prefix records each queen's column by row. For row m, that's prefix[m]. When I try column i in row level, I check against the queen in each earlier row: if i == prefix[m], they're in the same column; if level - m equals either i - prefix[m] or prefix[m] - i, they're on the same diagonal.

I place a queen only where neither check finds a conflict, and placing one in the last row completes the solution. I just add 1 to paths_count. This time I don't need to save each solution and then turn it into board strings. I keep paths_count on the Solution object, so the first thing I do in totalNQueens is reset it to zero. Otherwise, if I call it a second time on the same object, the result will include the count from the previous call.


Code

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
class Solution:

def __init__(self):
self.paths_count = 0

def dpTotalNQueens(self, n, prefix, level):
for i in range(0, n):
point = (i, level)
is_valid = True
for m in range(0, len(prefix)):
if i == prefix[m]:
is_valid = False
break
if level - m == i - prefix[m] or level - m == prefix[m] - i:
is_valid = False
break
if is_valid:
new_prefix = prefix[:]
new_prefix.append(i)
if n - 1 != level:
self.dpTotalNQueens(n, new_prefix, level + 1)
else:
self.paths_count += 1

# @return an integer
def totalNQueens(self, n):
# Clear the count left over from an earlier call on this object.
self.paths_count = 0
self.dpTotalNQueens(n, [ ], 0)
return self.paths_count

Article link: https://xnerv.wang/en/leetcode-n-queens-ii/