-
Notifications
You must be signed in to change notification settings - Fork 0
/
EightQueensProblem.java
60 lines (52 loc) · 1.75 KB
/
EightQueensProblem.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
package miscellaneous;
public class EightQueensProblem {
public static char[][] finalBoard;
private EightQueensProblem() {
}
public static boolean doesHaveEightQueensProblemSolution(int nth) {
char[][] board = new char[nth][nth];
for (int i = 0; i < nth; i++)
for (int j = 0; j < nth; j++)
board[i][j] = '-';
if (solveNQueens(board, 0, nth)) {
solution(board, nth);
finalBoard = board;
return true;
} else {
System.out.println("No solution exists");
finalBoard = new char[nth][nth];
return false;
}
}
public static void solution(char[][] board, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(" " + board[i][j] + " ");
System.out.println();
}
}
public static boolean isSafe(char[][] board, int row, int column, int n) {
int i, j;
for (i = 0; i < column; i++) {
if (board[row][i] == 'Q') return false;
}
for (i = row, j = column; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q') return false;
}
for (i = row, j = column; i < n && j >= 0; i++, j--) {
if (board[i][j] == 'Q') return false;
}
return true;
}
public static boolean solveNQueens(char[][] board, int column, int n) {
if (column >= n) return true;
for (int i = 0; i < n; i++) {
if (isSafe(board, i, column, n)) {
board[i][column] = 'Q';
if (solveNQueens(board, column + 1, n)) return true;
board[i][column] = '-';
}
}
return false;
}
}