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.用斜率公式判断。即横纵坐标之差绝对值不相等即可。

  • 相关阅读:
    shell脚本判断语句和循环语句
    shell脚本基础
    Linux防火墙(Firewalls)
    RAID磁盘阵列
    LVM逻辑卷创建管理
    vue与django结合使用
    Python使用pyecharts绘制cpu使用量折线图
    Centos8 网络配置静态IP
    Html表格处理
    django的教程相关
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9734828.html
Copyright © 2011-2022 走看看