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.
Example
Example 1:
Input:1
Output:
[["Q"]]
Example 2:
Input:4
Output:
[
// Solution 1
[".Q..",
"...Q",
"Q...",
"..Q."
],
// Solution 2
["..Q.",
"Q...",
"...Q",
".Q.."
]
]
Challenge
Can you do it without recursion?
思路:
这个题本质上也是一个排列问题,难点在于确定每个Q的位置,也就是visited的定义,然后语法不熟练的我也比较难画出结果,即使得到所有的列坐标。
皇后的行走规则是上下左右还有斜线,只要没有棋子就可以走,无论步数,转换成判断逻辑就是,竖直方向列坐标相同的点会冲突,横方向行坐标相同的点会冲突(在此题不需要考虑,因为一行只放一个皇后就可以), 斜方向横纵坐标差相等或者横纵坐标和相等的点会冲突。这样在visited里我们只需要存储放进去的皇后的列坐标,行坐标与列坐标的差,行坐标于列坐标的和就可以,只要新的皇后的位置不在visited里就可以满足条件。
代码: