-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAIassignment
More file actions
117 lines (101 loc) · 2.58 KB
/
AIassignment
File metadata and controls
117 lines (101 loc) · 2.58 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
public class main {
public static void main(String[] args) {
chessboard board = new chessboard();
board.start();
}
}
public class chessboard {
private static int board[][];
private int numQueens;
public chessboard(){
numQueens = 0;
board= new int[8][8];
for (int i=0;i<8;i++){
for (int j=0;j<8;j++){
board[i][j]=0;
}
}
}
public int getNumQueens(){
return numQueens;
}
public void start(){
solve(0);
}
public boolean solve(int numQueens){
if(numQueens==8){
System.out.println("Done");
this.printboard();
return true;
}
else{
for(int i=0; i<8; i++){
for(int j=0; j<8; j++){
if(isValid(i,j)==0){
this.placeQueen(i, j, 0);
numQueens++;
if(solve(numQueens)){
return true;
}else{
this.placeQueen(i, j, 1);
numQueens--;
}
}
}
}
}
return false;
}
public static int isValid(int x, int y){
for (int i=0; i<8; i++){
if(get(x,i)==1){
return -1;
}
if(get(i,y)==1) {
return -1;
}
}
for(int i=o; i<8; i++){
if(get(x-i,y-i)==1){
return -1;
}
if(get(x-i,y+i)==1){
return -1;
}
if(get(x+i,y-i)==1){
return -1;
}
if(get(x+i,y+i)==1){
return -1;
}
}
return 0;
}
public int placeQueen(int x, int y, int type){
if(type==0){
board[x][y]=1;
numQueens ++;
return 0;
}
else if(type==1){
board[x][y]=0;
return 0;
}
System.out.println ("wrong type");
return -3;
}
public static int get(int x, int y){
if(x<0 || y<0 || x>7 || y>7){
return -1;
}
return board[x][y];
}
public void printboard(){
for(int i=0; i<8; i++){
for(int j=0; j<8; j++){
System.out.print(this.get(i,j)+ " ");
}
System.out.println("");
}
}
}