N Queens

Get all valid ways of putting N Queens on an N * N chessboard so that no two Queens threaten each other.

Assumptions

N > 0

Return

A list of ways of putting the N Queens
Each way is represented by a list of the Queen's y index for x indices of 0 to (N - 1)

Example

N = 4, there are two ways of putting 4 queens:

[1, 3, 0, 2] --> the Queen on the first row is at y index 1, the Queen on the second row is at y index 3, the Queen on the third row is at y index 0 and the Queen on the fourth row is at y index 2.

[2, 0, 3, 1] --> the Queen on the first row is at y index 2, the Queen on the second row is at y index 0, the Queen on the third row is at y index 3 and the Queen on the fourth row is at y index 1.

class Solution(object):
    def nqueens(self, n):
      res = []
      self.dfs(n,0,[],res)
      return res
    
    def dfs(self,n,i,state.res):
      if i == n:
        res.append(state[:])
        return 
      for pos in xrange(n):
        if self.isValid(state,pos):
          state.append(pos)
          self.dfs(n,i+1,state,res)
          state.pop()
      return 
    
    def isValid(self,state,pos):
      for i in xrange(len(state)):
        if abs(state[i] - pos) in (0,len(state) - i):
          return False
      return True
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,093评论 0 23
  • 对道岔轨道静态几何尺寸允许偏差的规定,在分级与标准划分界面,与对线路的规定是一致的。因道岔在构造上比线路要复杂一些...
    155守时待命阅读 265评论 0 0
  • 买这本书的时候,还是今年刚入夏。而当我读完它的时候,正在准备迎接2016年的初雪。 是怎样的动机选中了这本书呢?或...
    小野椰子阅读 772评论 0 2
  • 传代1.取出细胞,观察(细胞密集情况)2.先倒掉培养液3.加入PBS冲洗,倒掉。再加入胰酶和PBS(1:1)4.摇...
    柳叶飘絮阅读 326评论 0 0