LeetCode 51. N-Queens--Python实现

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.

题意的要求简单来说就是在一个8*8的棋盘上摆上8个棋子,使它们不在同一行、同一列、同一斜线上。这题是一个很经典的问题。难点在问题的描述。这里我们使用一个数组board,board中元素下标代表第几行,元素值board[i]代表第i行Queen摆放的位置。下面来看这三个约束条件:

1.不同行:这个自然满足,数组board下标不同

2不同列:这个只要使board中各元素值不相同就行了。即board[i]!=board[j]

3.不同斜线:这个只要使board中元素相应的横纵坐标差的绝对值不等就行了。即|board[i]-board[j]|!=|i-j|

下面利用深度搜索即可。

class Solution(object):
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        def check(k,j):
            for i in range(k):
                if board[i]==j or abs(board[i]-j)==abs(k-i):
                    #Line 9: NameError: global name 'borad' is not defined 这个是为啥啊 拼写错误
                  #相应|X1-X2|=|Y1-Y2|
                    return False
            return True
        def dfs(depth,valuelist):
            if depth == n:
                res.append(valuelist)
                return 
            else:
                for i in range(n):
                    if check(depth,i):
                        board[depth]=i
                        s='.'*n
                        dfs(depth+1,valuelist+[s[:i]+'Q'+s[i+1:]])
        res=[]
        board = [-1 for i in range(n)]
        dfs(0,[])
        return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值