N-Queens II
LeetCode 52 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Backtracking that returns the number of solutions.
ನಾನು N-Queens II (LeetCode 52) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Constraint Satisfaction ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Same backtracking as N-Queens with O(1) attack checks, but return a count instead of building boards.
Approach
- 1
Base: col == n → 1.
- 2
Sum solutions over every safe row in this column.
- 3
Mark/unmark the row and both diagonals around the recursion.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Counting backtrackingPythonO(n!) time
class Solution:
def totalNQueens(self, n: int) -> int:
board = [["."]*n for _ in range(n)]
row_hash = [0]*n
bottom_left_diagonal = [0]*(2*n-1)
top_left_diagonal = [0]*(2*n-1)
def backtrack(col,board):
if col==n:
return 1
solutions = 0
for row in range(n):
if row_hash[row]==0 and bottom_left_diagonal[row+col]==0 and top_left_diagonal[n-1+col-row]==0:
board[row][col]="Q"
row_hash[row]=1
bottom_left_diagonal[row+col]=1
top_left_diagonal[n-1+col-row]=1
solutions+=backtrack(col+1,board)
board[row][col]="."
row_hash[row]=0
bottom_left_diagonal[row+col]=0
top_left_diagonal[n-1+col-row]=0
return solutions
return backtrack(0,board)
N-Queens II — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
N-Queens II ಹಿಂದಿನ intuition ಏನು?
Same backtracking as N-Queens with O(1) attack checks, but return a count instead of building boards.
N-Queens II (LeetCode 52) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Base: col == n → 1. 2. Sum solutions over every safe row in this column. 3. Mark/unmark the row and both diagonals around the recursion.
N-Queens II ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n!). Space: O(n). (Accepted approach: Counting backtracking.)
N-Queens II ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
The board array isn't needed for counting — the hashes are enough.