52. N-Queens II

Posted bernieloveslife

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了52. N-Queens II相关的知识,希望对你有一定的参考价值。

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 the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

class Solution:
    def totalNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        board = [-1] *n
        count = 0
        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):
            nonlocal count
            if line == n:
                count += 1
                return
            else:
                for i in range(n):
                    if safe(line,i):
                        board[line] = i
                        dfs(line + 1)
        dfs(0)
        return count

关键子nonlocal的作用与关键字global类似,使用nonlocal关键字可以在一个嵌套的函数中修改嵌套作用域中的变量












以上是关于52. N-Queens II的主要内容,如果未能解决你的问题,请参考以下文章

52. N-Queens II

52. N-Queens II

java 52. N-Queens II.java

java 52. N-Queens II.java

java 52. N-Queens II.java

java 52. N-Queens II.java