-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnQueens.java
80 lines (65 loc) · 2.06 KB
/
nQueens.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
import java.util.Scanner;
public class nQueens {
private static boolean check(int[][] board, int x, int y) {
for (int i = 0; i < board.length; i++) {
if (board[i][y] != 0) {
return false;
}
if (board[x][i] != 0) {
return false;
}
if (x - i >= 0 && y - i >= 0 && board[x - i][y - i] != 0) {
return false;
}
if (x + i < board.length && y + i < board.length && board[x + i][y + i] != 0) {
return false;
}
if (x - i >= 0 && y + i < board.length && board[x - i][y + i] != 0) {
return false;
}
if (x + i < board.length && y - i >= 0 && board[x + i][y - i] != 0) {
return false;
}
}
return true;
}
private static boolean queens(int n, int[][] board) {
if (n == 0) {
return true;
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j] == 0 && check(board, i, j)) {
board[i][j] = 1;
if (queens(n - 1, board)) {
return true;
}
board[i][j] = 0;
}
}
}
return false;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of queens: ");
int n = in.nextInt();
int[][] board = new int[n][n];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
board[i][j] = 0;
}
}
if (queens(n, board)) {
for (int[] i : board) {
for (int j : i) {
System.out.print(j + " ");
}
System.out.println();
}
} else {
System.out.println("No solutions found!");
}
in.close();
}
}