-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queens.java
108 lines (98 loc) · 2.68 KB
/
N-Queens.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import java.util.LinkedList;
import java.util.List;
public class Solution {
List<List<String>> solutions;
public List<List<String>> solveNQueens(int n) {
char[][] ans = new char[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
ans[i][j] = '.';
}
}
solutions = new LinkedList<List<String>>();
backTracker(ans, 0, n);
return solutions;
}
void backTracker(char[][] ans, int row, int n) {
if (row == n) {
List<String> solution = new LinkedList<String>();
for (int i = 0; i < n; i++) {
solution.add(new String(ans[i]));
}
solutions.add(solution);
return;
}
for (int i = 0; i < n; i++) {
ans[row][i] = 'Q';
if (isValidPlacement(ans, row, i, n)) {
backTracker(ans, row + 1, n);
}
ans[row][i] = '.';
}
}
boolean isValidPlacement(char[][] matrix, int row, int column, int n) {
// checking vertical
for (int i = 0; i < n; i++) {
if (i != row && matrix[i][column] == 'Q') {
return false;
}
}
// checking horizontal
for (int i = 0; i < n; i++) {
if (i != column && matrix[row][i] == 'Q') {
return false;
}
}
// NW direction
int i = row - 1;
int j = column - 1;
while (i >= 0 && j >= 0) {
if (matrix[i][j] == 'Q') {
return false;
}
i--;
j--;
}
// NE direction
i = row - 1;
j = column + 1;
while (i >= 0 && j < n) {
if (matrix[i][j] == 'Q') {
return false;
}
i--;
j++;
}
// SW direction
i = row + 1;
j = column - 1;
while (i < n && j >= 0) {
if (matrix[i][j] == 'Q') {
return false;
}
i++;
j--;
}
// SE direction
i = row + 1;
j = column + 1;
while (i < n && j < n) {
if (matrix[i][j] == 'Q') {
return false;
}
i++;
j++;
}
return true;
}
public static void main(String[] args) {
Solution solver = new Solution();
List<List<String>> solutions = solver.solveNQueens(4);
for (List<String> solution : solutions) {
for (String row : solution) {
System.out.println(row);
}
System.out.println();
}
}
}