leetcode 51 n皇后
题目描述:
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
题目分析:
- 首先看到题目需要我们找到皇后所有的可能摆放位置,那么肯定需要我们遍历所有可能的空间,同时在尝试的摆放方案不合理时直接退回上一步。
- 直觉的方法就是递归,同时传递一个list来记录之前尝试的皇后的位置,每一次迭代时首先根据传递进来的list计算不会被之前的皇后攻击的位置,然后在list append本轮的皇后位置后在递归,返回时记得把本轮append上去的皇后的位置pop掉。
Python代码
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
if not n:
return [[]]
if n == 1:
return [['Q']]
if n < 4:
return []
res = []
def recur_find(q_list):
if len(q_list) == n:
temp = []
for i in q_list:
temp_res = ['.' for j in xrange(n)]
temp_res[i] = 'Q'
temp.append(''.join(temp_res))
res.append(temp)
return
danger_list = set()
for level, pos in enumerate(q_list):
pos_l = pos - (len(q_list)) + level if pos - (len(q_list)) + level >= 0 else None
pos_r = pos + (len(q_list)) - level if pos + (len(q_list)) - level <= n - 1 else None
if pos_l is not None:
danger_list.add(pos_l)
if pos_r is not None:
danger_list.add(pos_r)
danger_list.add(pos)
for i in xrange(n):
if i in danger_list:
continue
q_list.append(i)
recur_find(q_list)
q_list.pop()
recur_find([])
return res