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

leetcode -- N-Queens

2013-08-11 14:18 267 查看
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.."]
]


public class Solution {
public static void main(String[] args) {
ArrayList<String[]> result = solveNQueens(4);
System.out.println(result.size());
for(int i = 0; i < result.size(); i++){
System.out.println("solution:" + i);
for(int j = 0; j < result.get(i).length; j++){
System.out.println(result.get(i)[j]);
}
}
}

public static ArrayList<String[]> solveNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<String[]> result = new ArrayList<String[]>();
int depth = 0;
int[] rows = new int
;
for (int i = 0; i < n; i++) {
rows[i] = n + 1;
}
dfs(depth, rows, n, result);
return result;
}

public static void dfs(int depth, int[] rows, int n, ArrayList<String[]> result) {
if (depth == n) {
String[] s = new String
;
for (int i = 0; i < n; i++) {
int m = rows[i];
StringBuilder tmp = new StringBuilder();
for (int j = 0; j < n; j++) {
if (j == m) {
tmp.append("Q");
continue;
}
tmp.append(".");
}
s[i] = tmp.toString();
}
result.add(s);
return;
}
for (int i = 0; i < n; i++) {
rows[depth] = i;
if (isValid(rows, depth)) {
dfs(depth + 1, rows, n, result);
}
}

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