zoukankan      html  css  js  c++  java
  • 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.

    For example,
    There exist two distinct solutions to the 4-queens puzzle:

    [
     [".Q..",  // Solution 1
      "...Q",
      "Q...",
      "..Q."],
    
     ["..Q.",  // Solution 2
      "Q...",
      "...Q",
      ".Q.."]
    ]

    N皇后的题目听传闻已久。主要是在一个n*n的板上布上n个棋子,这n个棋子不能在同一行同一列,也不能在同一条对角线上。本身这题有非常多的解法。但是用代码求解的方式,也就是暴力枚举的方法,复杂度是指数的,毕竟方案数目一共就是指数多个。这种需要求出所有组合的方式基本就是深搜DFS来解了。另外注意这种方式需要结合回溯来做。

    这题的重点在于检查皇后是否同行同列。因为我们每一行只放置一个皇后,所以很好的解决了同一行的问题,所以剩下的还需要解决的问题是同列。1.一个解决方案是维护像Permutations中这样的used数组,已经枚举过的列不再枚举,防止重复。2.另外一种是直接检查。对于当前的位置,检查前面每一行在当前这一列是否有皇后。对于对角线问题,一个是正对角线,一个是斜对角。对角线的特征是:组成对角线的两点,横向距离等于纵向距离,组成了正方形。

    代码如下:

    class Solution(object):
        def solveNQueens(self, n):
            """
            :type n: int
            :rtype: List[List[str]]
            """
            res = []
            cur = []
            self.helper( res, cur, n)
            return res
        def  helper(self, res, cur, n):
             if len(cur) == n:
                 item = [['.']*n for i in xrange(n)] 
                 for i in xrange(n):
                     item[i][cur[i]] = 'Q'
                     item[i] = ''.join(item[i])
                 res.append(item+[])
                 return
             for i in xrange(n):
                 if self.check(cur, i):
                     continue
                 cur.append(i)
                 self.helper(res, cur, n)
                 cur.pop()
        def check(self, cur, i):    #检查是否合格
            row = len(cur)
            for j in xrange(row):
                if row - j == abs(cur[j] - i) or cur[j] == i: #前面检查是否在一条对角线上,后面解决是否在同一列上。
                    return True
            return False

    这题在每次取一点时都要用O(i)的时间去检查,组成一个方案需要O(n^2)时间,一共n!方案,所以最终复杂度为O(n^2*n!).空间复杂度为O(n).

  • 相关阅读:
    css样式兼容不同浏览器问题解决办法
    css 中input和select混排对齐问题
    盒模型详解
    css中的width,height,属性与盒模型的关系
    php中将文中关键词高亮显示,快捷方式可以用正则
    数据库面试知识
    ConcurrentHashMap原理分析(1.7与1.8)
    Docker 学习笔记
    秒杀系统架构分析与实战
    spring + redis 实现数据的缓存
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5627123.html
Copyright © 2011-2022 走看看