-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestClass.java
91 lines (79 loc) · 2.64 KB
/
TestClass.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
81
82
83
84
85
86
87
88
89
90
91
/* IMPORTANT: Multiple classes and nested static classes are supported */
/*
* uncomment this if you want to read input.
//imports for BufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;
*/
//import for Scanner and other utility classes
import java.util.*;
// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
class TestClass {
public int board[][];
public int n;
TestClass(int N){
board = new int[N][N];
n=N;
}
public boolean isAtacked(int x, int y){
//Check for row and column
for(int i=0;i<n;i++)
if(board[x][i]==1 || board[i][y]==1)
return true;
//Check for digonal
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(x-y == i-j){
if(board[i][j]==1)
return true;
}
if(x+y == i+j){
if(board[i][j]==1)
return true;
}
}
}
return false;
}
//This function will call itself re
public boolean findQueens(int N,int row){
if(N==0){
return true;
}
for(int j=0;j<n;j++){
if(!isAtacked(row,j)){
board[row][j] = 1; //Place current queen at cell (row,j)
if(findQueens(N-1,row+1)){ // Solve subproblem
return true; // if solution is found return true
}else{
board[row][j] = 0; /* if solution is not found undo whatever changes
were made i.e., remove current queen from (row,j)*/
}
}
}
return false;
}
public static void main(String args[] ) throws Exception {
/* Sample code to perform I/O:
* Use either of these methods for input
*/
//Scanner
Scanner s = new Scanner(System.in);
System.out.println("Please Enter the size of board (eg:for 4x4 enter 4)");
int N = s.nextInt();
TestClass obj = new TestClass(N);
if(obj.findQueens(N,0)){
System.out.println("Yes");
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
System.out.print(obj.board[i][j]+ " ");
}
System.out.println();
}
}else{
System.out.println("NO");
}
s.close();
// Write your code here
}
}