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.
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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-n-queens-ii/

