代码思路:用三个set标记当前位置所在的行、主、次对角线方向上是否合法。
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
# 返回值
res = []
# 皇后
queens = [-1] * n
# 列
columns = set()
# 主对角线方向
dia1 = set()
# 次对角线方向
dia2 = set()
self.helper(queens, columns, dia1, dia2, res, n, 0)
return res
def helper(self, queens, columns, dia1, dia2, res, n, row):
if row == n:
path = self.drawPath(queens, n)
res.append(path)
else:
for i in range(n):
# if columns[i]: continue
# d1 = row - i
# if dia1[d1]: continue
# d2 = row + i
# if dia2[d2]: continue
if i in columns or row - i in dia1 or row + i in dia2:
continue
queens[row] = i
columns.add(i)
dia1.add(row - i)
dia2.add(row + i)
# 递归
self.helper(queens, columns, dia1, dia2, res, n, row + 1)
# 回退
columns.remove(i)
dia1.remove(row - i)
dia2.remove(row + i)
def drawPath(self, queens, n):
path = []
row = ["."] * n
for i in range(n):
row[queens[i]] = "Q"
path.append("".join(row))
row[queens[i]] = "."
return path