1. 程式人生 > 實用技巧 >[Leetcode] 51. N皇后

[Leetcode] 51. N皇后

題目連結:https://leetcode-cn.com/problems/n-queens/
分析:
x&(-x)保留最後一位的1,其它位置全部置零
x&(x-1)最後一個1置零。availablePos用1表示可以放置的地方,而columns,diagnolL, diagnolR用1表示不可用的位置。
Python

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        def generateBoard():
            board = []
            for i in queen:
                tmp = ['.']*n
                tmp[i] = 'Q'
                board.append(''.join(tmp))
            return board

        def solve(row, columns, diagnolL, diganolR):
            if  row == n:
                res.append(generateBoard())
                return 
            else:
                availablePos = ((1<<n)-1)&(~(columns|diagnolL|diganolR))
                
                while availablePos:
                    column = availablePos & (-availablePos)
                    availablePos &= (availablePos-1)
                    pos = bin(column-1).count('1')
                    queen[row] = pos 
                    solve(row+1, columns|column, (diagnolL|column)<<1, (diganolR|column)>>1)
        queen = [-1]*n
        res = []
        solve(0, 0, 0, 0)
        return res