Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 6. 5. 23:45

https://leetcode.com/problems/n-queens-ii/

 

N-Queens II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

N-Queens.. again..?
아 hard는 넘 어려운듯..

다행히 어제 푼 문제에서 답의 갯수만 표시를 하면 되서 소스는 조금 더 간단해진다.

class Solution:
    def totalNQueens(self, n: int) -> int:
        column = [0] * n
        diag1, diag2 = [0] * (2 * n - 1), [0] * (2 * n - 1)
        self.res = 0
        
        def search(y):
            if y == n:
                self.res += 1
                return
            for x in range(n):
                if column[x] or diag1[x+y] or diag2[x-y+n-1]:
                    continue
                column[x] = diag1[x+y] = diag2[x-y+n-1] = y+1
                search(y+1)
                column[x] = diag1[x+y] = diag2[x-y+n-1] = 0
        search(0)
        
        return self.res
반응형