-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.java
More file actions
96 lines (85 loc) · 2.54 KB
/
Game.java
File metadata and controls
96 lines (85 loc) · 2.54 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
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
import java.util.Arrays;
public class Game {
private Figure[][] figureField = new Figure[8][8];
private int fieldsize = 8;
private int solutionCount = 1;
private void init(int size) {
figureField = new Figure[size][size];
fieldsize = size;
}
private boolean set(int x, int y, Figure figure, Figure[][] field) {
if (field[x][y] instanceof Figure) {
return false;
}
field[x][y] = figure;
return true;
}
private boolean remove(int x, int y, Figure[][] field) {
if (field[x][y] instanceof Figure) {
field[x][y] = null;
return true;
}
return false;
}
private void backtracking(boolean print) {
if (print) {
dfs(0, figureField, true);
}
}
private boolean dfs(int x, Figure[][] field, boolean print) {
if (goalReached(field)) {
if (print) {
print();
}
return true;
}
for (int y = 0; y < fieldsize; y++) {
Queen q = Queen.getInstance(x, y);
if (!q.isYQueenCross(y, field, fieldsize)
&& check(field, x, y)) {
set(x, y, q, field);
dfs(x + 1, field, print);
remove(x, y, field);
continue;
}
}
return false;
}
boolean check(Figure[][] field, int X, int Y) {
for (int y = 0; y < fieldsize; y++) {
for (int x = 0; x < fieldsize; x++) {
if (field[x][y] == null) {
continue;
}
if (field[x][y].move(X, Y)) {
return false;
}
}
}
return true;
}
private boolean goalReached(Figure[][] field) {
for (Figure[] x : field) {
if (!Arrays.stream(x).anyMatch(figure -> figure instanceof Queen)) {
return false;
}
}
return true;
}
private void print() {
System.out.println(String.format("Solution %d:", solutionCount));
solutionCount++;
for (int y = 0; y < fieldsize; y++) {
for (int x = 0; x < fieldsize; x++) {
System.out.print((figureField[x][y] == null ? "X" : figureField[x][y]) + " ");
}
System.out.print("\n");
}
System.out.println();
}
public static void main(String... args) {
Game game = new Game();
game.init(8);
game.backtracking(true);
}
}