N-Queens

问题:N皇后问题,给定一个正整数n,输出在n*n的方格中所有的皇后问题的解决办法

示例:



python代码:
class Solution(object):
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        if not n:
            return []
        elif n == 1:
            return [["Q"]]
        else:
            self.out = []
            self.Queen(n)
            return self.out
        
    def Queen(self,n,row=0,ele=[],col_use=[],dia_l=[],dia_r=[]):
        if row == n:
            self.out.append(ele)
            return
        for col in range(n):
            flag = False
            if col in col_use or (col+row) in dia_l or (col-row) in dia_r:
                continue
            else:
                flag = True
                self.Queen(n,row+1,ele+["."*col+"Q"+(n-col-1)*"."],col_use+[col],dia_l+[col+row],dia_r+[col-row])
        if not flag:
            return

 

 
posted @ 2019-06-13 13:23  秦qin  阅读(131)  评论(0编辑  收藏  举报