Skip to content

Latest commit

 

History

History
52 lines (35 loc) · 1016 Bytes

052._n-queens_ii.md

File metadata and controls

52 lines (35 loc) · 1016 Bytes

###52. N-Queens II

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

难度: Hard

思路参见recursion & backtracking

n queens还是属于比较难的,需要花时间吃透的问题



class Solution(object):
    def totalNQueens(self, n):
        """
        :type n: int
        :rtype: int
        """
        self.board = []
        self.cnt = 0
        self.placequeen(0,n)
        return self.cnt

    def danger(self, board ,row, col):
        for (i, j) in board:
            if row == i: return True
            if col == j: return True
            if abs(row - i) == abs(col - j): return True

        return False


    def placequeen(self, row, n):
        if row >= n:
            #print self.board
            self.cnt +=1
        else:
            for col in range(0, n):
                if not self.danger(self.board, row, col):
                    self.board.append((row, col))
                    self.placequeen(row + 1, n)
                    self.board.remove((row,col))