Skip to content

Latest commit

 

History

History
48 lines (37 loc) · 1.1 KB

051._n-queens.md

File metadata and controls

48 lines (37 loc) · 1.1 KB

###51. N-Queens

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

难度: Hard

偷懒,用52, 依旧需要挖掘

class Solution(object):
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        self.board = []
        self.res = []
        self.placequeen(0,n)
        return self.res

    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:
            tmpRes = [['.' for i in range(n)] for j in range(n)]
            for (row,col) in self.board:
                tmpRes[row][col] = 'Q'
            tmpRes = [''.join(i) for i in tmpRes]
            self.res.append(tmpRes)

        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))