51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

class Solution:
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        board = [-1] *n
        res = []
        def safe(a,b):
            for i in range(a):
                if board[i]==b or abs(board[i]-b)==abs(a-i):
                    return False
            return True
        def dfs(line,temp):
            if line == n:
                res.append(temp)
                return
            else:
                for i in range(n):
                    if safe(line,i):
                        board[line] = i
                        s = '.'*n
                        dfs(line + 1,temp + [s[:i] + 'Q' + s[i+1:]])
        dfs(0,[])
        return res

tip1.使用一维数组记录列数,可以减少空间复杂度到O(n)
tip2.所谓在一条斜线上,也就是斜率为正负1.用斜率公式判断。即横纵坐标之差绝对值不相等即可。

原文地址:https://www.cnblogs.com/bernieloveslife/p/9734828.html