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

Leet Code 51 N-Queens - N皇后问题 - Java

2016-06-23 00:00 211 查看
摘要: Leet Code 51 N-Queens - N皇后问题 - Java

问题原始链接 https://leetcode.com/problems/n-queens

N皇后问题,在 N*N 的棋盘上放 N 个皇后,任意两个皇后不相互攻击。

给定整数 n,返回 n皇后的所有不同的解。

解中 'Q' 和 '.' 分别表示皇后和空格子。

例如,4皇后问题有两个不同的解:

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

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

public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<List<String>>();
if (n <= 0) {
return result;
}
place(new int
, 0, new StringBuilder(n), result);
return result;
}

private static void place(int[] rowToCol, int row, StringBuilder printer,
List<List<String>> result) {
if (row == rowToCol.length) {
print(rowToCol, printer, result);
return;
}

for (int col = 0; col < rowToCol.length; col++) {
rowToCol[row] = col;
if (!isAttack(rowToCol, row)) {
place(rowToCol, row + 1, printer, result);
}
}
}

private static boolean isAttack(int[] rowToCol, int row) {
for (int preRow = 0; preRow < row; preRow++) {
if (Math.abs(row - preRow) == Math.abs(rowToCol[preRow] - rowToCol[row])
|| rowToCol[row] == rowToCol[preRow]) {
return true;
}
}
return false;
}

private static void print(int[] rowToCol, StringBuilder printer,
List<List<String>> result) {
List<String> solution = new ArrayList<String>();
for (int row = 0; row < rowToCol.length; row++) {
solution.add(printRow(rowToCol, row, printer));
}
result.add(solution);
}

private static String printRow(int[] rowToCol, int row, StringBuilder printer) {
printer.setLength(0);
for (int col = 0; col < rowToCol[row]; col++) {
printer.append(".");
}
printer.append("Q");
for (int col = rowToCol[row] + 1; col < rowToCol.length; col++) {
printer.append(".");
}
return printer.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息