forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_51.java
70 lines (59 loc) · 1.91 KB
/
_51.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
public class _51 {
public static class Solution1 {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<>();
if (n <= 0) {
return result;
}
search(n, new ArrayList<>(), result);
return result;
}
private void search(int n, ArrayList<Integer> col, List<List<String>> result) {
if (col.size() == n) {
result.add(drawChessBoard(col));
return;
}
for (int i = 0; i < n; i++) {
if (!isValid(col, i)) {
continue;
}
col.add(i);
search(n, col, result);
col.remove(col.size() - 1);
}
}
private boolean isValid(ArrayList<Integer> col, int next) {
int row = col.size();
for (int i = 0; i < row; i++) {
if (next == col.get(i)) {
return false;
}
if (i - row == col.get(i) - next) {
return false;
}
if (i - row == next - col.get(i)) {
return false;
}
}
return true;
}
private ArrayList<String> drawChessBoard(ArrayList<Integer> col) {
ArrayList<String> chessBoard = new ArrayList<>();
for (int i = 0; i < col.size(); i++) {
String row = "";
for (int j = 0; j < col.size(); j++) {
if (col.get(j) == i) {
row += "Q";
} else {
row += ".";
}
}
chessBoard.add(row);
}
return chessBoard;
}
}
}