The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 Given an integer n, return all distinct solutions to the n-queens puzzle. 给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。 Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively. 每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。
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.在放置每个皇后以后增加限制。当在棋盘上放置了一个皇后后,立即排除当前行,列和对应的两个对角线。 约束编程有助于减少需要考虑情况数。
Q: 当选择的方案不是最优的,无法放置下一个皇后时,此时我们该怎么做? A: 回溯。 意思是回退一步,来改变最后放置皇后的位置并且接着往下放置。如果还是不行,再 回溯。