题目
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。
示例:
输入: 4
输出: [
[".Q…", // 解法 1
“…Q”,
“Q…”,
“…Q.”],
["…Q.", // 解法 2
“Q…”,
“…Q”,
“.Q…”]
]
解释: 4 皇后问题存在两个不同的解法。
思路
一行一行去做dfs index代表行号,从0开始
因为不肯能在同一行放两个皇后。
加三个标记数组:
如果这一行有皇后,就标记为为True,col[i]代表第i列有皇后
col = defaultdict(bool)
第一类对角线上有皇后,标记为True
dia1 = defaultdict(bool)
# 第一类对角线行和列号相加总是为常数
第二类对角线上有皇后,标记为True
dia2 = defaultdict(bool)
# 第二类对角线行和列号相减总是为常数
python代码
from collections import defaultdict
import copy
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
if n <= 0:
return []
col = defaultdict(bool)
dia1 = defaultdict(bool)
dia2 = defaultdict(bool)
res = []
row = []
ans = []
def dfs(index):
if index == n:
res.append(copy.copy(row))
return
for i in range(n):
if not col[i] and not dia1[index + i] and not dia2[index-i]:
col[i] = True
dia1[index+i] = True # 第一类对角线行和列号相加总是为常数
dia2[index-i] = True # 第二类对角线行和列号相减总是为常数
row.append(i)
dfs(index+1)
col[i] = False
dia1[index+i] = False
dia2[index-i] = False
row.remove(i)
dfs(0)
print(res)
for k in range(len(res)):
graph = []
for i in range(n):
temp = ""
for j in range(n):
if j == res[k][i]:
temp += "Q"
else:
temp += "."
if j == n-1:
graph.append(temp)
ans.append(graph)
return ans