码迷,mamicode.com
首页 > 其他好文 > 详细

52. N-Queens II

时间:2018-10-02 17:44:54      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:example   self   number   input   boa   关键字   tac   solution   ...   

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

标签:example   self   number   input   boa   关键字   tac   solution   ...   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!