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

  • 相关阅读:
    火币Huobi API Websocket
    火币Huobi API
    OKEX API(Websocket)
    OKEX API
    Linux下Miniconda量化环境安装
    Numba:高性能Python编译器
    十进制和十六进制互相转换
    JavaScript 原型和原型链
    Redux 进阶之 react-redux 和 redux-thunk 的应用
    Vue 中 $nextTick() 的应用
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9734828.html
Copyright © 2011-2022 走看看