-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueens.java
More file actions
49 lines (37 loc) · 1 KB
/
Copy pathNQueens.java
File metadata and controls
49 lines (37 loc) · 1 KB
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
public class Solution {
public static void placeNQueens(int n){
for (int i = 0; i < n; i++){
int[] column = new int[n];
column[0] = i;
placeNQueens(column, 1);
}
}
public static void placeNQueens(int[] column, int j){
int n = column.length;
if (j == n){
for (int i = 0; i < n; i++){
for (int k = 0; k < n; k++){
if (k == column[i]){
System.out.print(1+" ");
}
else System.out.print(0+" ");
}
}
System.out.println();
return;
}
int[] row = new int[n];
for (int i = 0; i < j; i++){
int index = column[i];
row[index] = 1;
if (index + (j-i) < n) row[index + (j-i)] = 1;
if (index - (j-i) >= 0) row[index - (j-i)] = 1;
}
for (int i = 0; i < n; i++){
if (row[i] == 0){
column[j] = i;
placeNQueens(column, j+1);
}
}
}
}