# [刷题]N-Queens

[LintCode]N-Queens

class Solution {
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
ArrayList<ArrayList<String>> solveNQueens(int n) {
// 2015-07-07
ArrayList<ArrayList<String>> rst = new ArrayList<>();
if (n == 0) {
return rst;
}
ArrayList<Integer> list = new ArrayList<>();
helper(rst, list, n);
return rst;
}

private void helper(ArrayList<ArrayList<String>> rst, ArrayList<Integer> list ,int n) {
// 控制树的深度
if (list.size() == n) {
return;
}

for (int i = 0; i < n; i++) {
// 控制分支
if (!isValid(list, i)) {
continue;
}
helper(rst, list, n);
list.remove(list.size() - 1);
}
return;
}

// 将数组转为string组
private ArrayList<String> convert(ArrayList<Integer> list) {
ArrayList<String> rst = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
String s = new String("");
for (int j = 0; j < list.size(); j++) {
if (j == list.get(i)) {
s += "Q";
} else {
s += ".";
}
}
}
return rst;
}

// 判断是queen是否可以相互攻击
private boolean isValid(ArrayList<Integer> list, int k) {
if (list.size() == 0) {
return true;
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == k) {
return false;
}
if (list.get(i) - i == k - list.size()) {
return false;
}
if (list.get(i) + i == k + list.size()) {
return false;
}
}
return true;
}
};


• 本文已收录于以下专栏：

举报原因： 您举报文章：[刷题]N-Queens 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)