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).

  • 相关阅读:
    查询数据库版本
    Appscan的安装破解以及使用
    jmeter接口性能测试【CSV文件读取+接口关联+设置集合点】
    常用命令记录
    jmeter接口自动化-通过csv文件读取用例并执行测试
    js函数
    js数据类型及方法
    初识js(第一篇)
    一个人记笔记多没意思啊,拿出来分享一下咯
    博客园设置访问数量统计-小试牛刀
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5627123.html
Copyright © 2011-2022 走看看