英文原题
The n-queens puzzle is the problem of placing n queens on an n x 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.
分析
queens能进攻的范围是米字(横竖再加两个斜线)。这题得用递归搜索构建棋盘,一行一行构建,很明显每一行只能放一个’Q’,接下来要考虑的就是新的一行的’Q’和斜线,竖线两个方向的冲突。我用(x1, y1) 和 (x2, y2)来表示两个’Q’: - 竖线方向:x1 != x2 - 左上到右下的斜线:(x1-y1)+n-1 != (x2-y2)+n-1 - 右上到左下的斜线:x1+y1 != x2+y2 满足以上条件两个’Q’就不冲突。
python 代码
board是构建的棋盘,board_s是用来记录目前depth前面的’Q’位置的情况。
1 | class Solution: |