描述
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..”]
]
分析
这道题非常经典,最基础的做法就是DFS回溯。还有很多优化加速的方法,比如对角线缓存法。
代码
回溯
1 | class Solution(object): |
缓存对角线加速
1 | class Solution(object): |