您的位置:首页 > 产品设计 > UI/UE

N-Queens 解答

2015-10-18 03:50 507 查看

Question

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.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[".Q..",  // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.",  // Solution 2
"Q...",
"...Q",
".Q.."]
]

Solution

N-queens问题是NP问题。基本思想其实是用brute-force列举出所有可能然后检查。

这里我们可以用一维数组来表示棋盘。A[rowNum] = colNum代表(rowNum, colNum)处是queen。

用迭代的方法进行层层遍历。

到第x行时,说明前(x - 1)行的queen放置都合法。

那我们就遍历前(x - 1)行的结果,如果当前第x行放置的点:

1. 列的值与之前的重复 --> false

2. (行 + 列)或 (行 - 列)的值和之前的 (行 + 列)或(行 - 列)的值相同 --> false

注意对于这题,因为是用一维数组表示棋盘,所以我们不用恢复迭代时设置的queen的位置值。

(参考:CodeGanker, 小莹子

public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<List<String>>();
// Here, we use a 1-D array to represent queen positions
// queen[1] = 2 means that on (1, 2), there is a queen
int[] queen = new int
;
helper(n, 0, result, queen);
return result;
}

private void helper(int n, int rowNum, List<List<String>> result, int[] queen) {
if (rowNum == n) {
List<String> oneResult = new ArrayList<String>();
// Current chess board is valid
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder(n);
int tmp = n;
while (tmp > 0) {
sb.append(".");
tmp--;
}
int column = queen[i];
sb.replace(column, column + 1, "Q");
oneResult.add(sb.toString());
}
result.add(oneResult);
return;
}

for (int i = 0; i < n; i++) {
queen[rowNum] = i;
if (check(rowNum, queen))
helper(n, rowNum + 1, result, queen);
}
}

private boolean check(int rowNum, int[] queen) {
int colNum = queen[rowNum];
for (int i = 0; i < rowNum; i++) {
if (queen[i] == colNum || (queen[i] + i == rowNum + colNum) || (queen[i] - i == colNum - rowNum))
return false;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: