51. N-Queens
Posted bernieloveslife
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
class Solution:
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
board = [-1] *n
res = []
def safe(a,b):
for i in range(a):
if board[i]==b or abs(board[i]-b)==abs(a-i):
return False
return True
def dfs(line,temp):
if line == n:
res.append(temp)
return
else:
for i in range(n):
if safe(line,i):
board[line] = i
s = ‘.‘*n
dfs(line + 1,temp + [s[:i] + ‘Q‘ + s[i+1:]])
dfs(0,[])
return res
tip1.使用一维数组记录列数,可以减少空间复杂度到O(n)
tip2.所谓在一条斜线上,也就是斜率为正负1.用斜率公式判断。即横纵坐标之差绝对值不相等即可。
以上是关于51. N-Queens的主要内容,如果未能解决你的问题,请参考以下文章