递归和回溯_leetcode52

class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype:
"""
self.col = [False for i in range(n)]
self.diaS = [False for i in range(2 * n - 1)]
self.diaN = [False for i in range(2 * n - 1)]

ans = []
self.res = 0

self.putQueen(n, 0, ans)

print self.res



# 尝试在一个n皇后的问题中,摆放第index行皇后的位置

def putQueen(self, n, index, ans):
if index == n:
self.res += 1
# self.res.append(ans[0:])

return

# 尝试将第index行的皇后摆放在第i列
for i in range(n):
if not self.col[i] and not self.diaS[index + i] and not self.diaN[index - i + n - 1]:
ans.append(i)

self.col[i] = True
self.diaS[index + i] = True
self.diaN[index - i + n - 1] = True

self.putQueen(n, index + 1, ans)

ans.pop()
self.col[i] = False
self.diaS[index + i] = False
self.diaN[index - i + n - 1] = False

return


posted @ 2019-03-19 10:30  AceKo  阅读(147)  评论(0编辑  收藏  举报