经典的八皇后问题的延伸,利用回溯算法可以轻松求解,文中还给出了另外一种利用位图(bit manipulations)的做法。
问题描述
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.
思路
方法一:
经典的回溯问题,我们可以定义一个一维数组int x[n]
来表示第i
行,我们把皇后放在了第x[i]
列。所以当判断第k行,我们把皇后放在x[k]是否合理,我们可以如下判断:
- 该列上是否有其她皇后
- 斜率为1的直线上是否有皇后
- 斜率为-1的直线上是否有皇后
注意:判断斜率为1和-1的直线时,利用求直线斜率的公式,转变为:
$$
|i - k| == |x[i] - x[k]|
$$
|
|
方法二:
利用 bit manipulations 求解,首先定义了三个向量:
- row:为1的地方说明不能放皇后
- ld:斜率为1的直线,为1的地方说明不能放皇后
- rd:斜率为-1的直线,为1的地方说明不能放皇后
核心: available = board & (~(row | ld | rd))
board 为111…111(n个1)
简单的例子示意图(4皇后):
求出可放位置后,经过转换,到下一步:
Code
方法一:
|
|
方法二:
|
|