Description
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.
解法
经典的算法问题:N皇后问题。先解释一下:皇后不能同时出现在同一列,同一行或在同一条斜边上。为了找出所有可能的摆放,我们按行进行搜索,每一行寻找一个可以摆放的位置,如果合法,则进行下一行的搜索,当那一行不存在合法的摆放时,回溯归位。就是典型的回溯法解题啦~此题的关键在于数据结构的设计,巧妙地使用一维数组记录每一行皇后的j坐标可以将算法的设计大大简化。
具体代码如下:
1 | class Solution { |