zoukankan      html  css  js  c++  java
  • 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.用斜率公式判断。即横纵坐标之差绝对值不相等即可。

  • 相关阅读:
    函数的定义
    函数名的本质
    函数进阶
    三元运算
    数据类型 补充
    安装python问题
    neo4j nosql图数据库学习
    ubutun lunix 64安装neo4j 图形数据库
    git error: object file .git/objects/b9/e269f50db2a3415cc8ad5ba40b82b9b6a13d45 is empty
    django orm 时间处理
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9734828.html
Copyright © 2011-2022 走看看