-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEightQueens.java
More file actions
54 lines (54 loc) · 1.36 KB
/
EightQueens.java
File metadata and controls
54 lines (54 loc) · 1.36 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
import java.util.*;
//how many ways can you place 8 queens on a board without them attacking each other
//recursive backtracking: build the solution incrementally, when it doesn't work, go back to the last point it was right
//it allows you to cut off all the other possibilities down that branch if you cut the bud off early. saves you iterations
public class EightQueens {
public static void main(String[] args) throws InterruptedException
{
Stack<int[]> checkpoints = new Stack<int[]>();
int[] temp;
for (int i = 0; i < 8; i ++)
{
temp = new int[2];
temp[0] = i; //coord[0] ---> row
temp[1] = 0; //coord[1] ---> col
checkpoints.add(temp);
}
int[] currentSol = new int[8];
int row, col;
boolean isSolution;
int count = 0;
while (!checkpoints.isEmpty())
{
temp = checkpoints.pop();
row = temp[0];
col = temp[1];
isSolution = true;
for (int i = 0; i < col; i++)
{
if (currentSol[i] == row || Math.abs(currentSol[i] - row) == Math.abs(i - col))
{
isSolution = false;
break;
}
}
if (isSolution)
{
if (col == 7)
count++;
else
{
for (int i = 0; i < 8; i ++)
{
temp = new int[2];
temp[0] = i; //coord[0] ---> row
temp[1] = col + 1; //coord[1] ---> col
checkpoints.add(temp);
}
currentSol[col] = row;
}
}
}
System.out.println(count);
}
}