这是leetcode的第51题–N-Queens
题目
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
思路
利用递归,依次摆放第i个皇后,注意要求的返回结果是字符串,imutable,不可变,所以先用列表,然后join
show me the code
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
rst = []
nums = [0]*n
def abs(x):
if x > 0:
return x
return -x
def find(i):
if i == n:
tmp = []
for count,index in enumerate(nums):
s = ['.']*n
s[index] = 'Q'
tmp.append(''.join(s))
rst.append(tmp)
return
for j in range(0,n):
ok = True
for index,k in zip(range(i),nums):
if abs(index-i) == abs(j-k) or k == j:
ok = False
break
if not ok:
continue
nums[i] = j
find(i + 1)
find(0)
return rst