每天两道LeetCodeHard:(9)

182 阅读1分钟

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.

解释:

难得一见的题干比较复杂的题目,这个题要求我们在n*n的棋盘上放置n个皇后,这里要普及一下皇后的规则,主要有3条: 1,同一列只能有一个 2,同一行只能有一个 3,同一对角线只能有一个 要求我们返回所有可能的放置策略

思考:

一开始的想法是建立4个visited数组,分别代表4个线,对每一个坐标进行暴力dfs+回溯,但是感觉这样复杂度要爆炸。 然后看了看评论区,发现真的是这样,按照行来每行分配一个皇后保证不冲突即可。。 (这题hard到底是为什么?)

答案:

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        def DFS(queens,xy_dif,xy_sum):
            p=len(queens)
            if p == n:
                result.append(queens)
                return
            for q in range(n):
                if q not in queens and p-q not in xy_dif and p+q not in xy_sum:
                    DFS(queens+[q],xy_dif+[p-q],xy_sum+[p+q])
        result =[]
        DFS([],[],[])
        return [["."*i+"Q"+"."*(n-i-1) for i in sol] for sol in result]

答案补充:

实在是非常的简洁,这种代码风格要好好学习一下,查重思路清晰。