Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 52 · Constraint Satisfaction

N-Queens II

LeetCode 52 · கடினம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Backtracking that returns the number of solutions.

கடினம்BacktrackingAlgorithm X
LeetCode இல் திற ↗

நான் 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. 1

    Base: col == n → 1.

  2. 2

    Sum solutions over every safe row in this column.

  3. 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.