forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueen_Problem.java
More file actions
83 lines (77 loc) · 2.1 KB
/
NQueen_Problem.java
File metadata and controls
83 lines (77 loc) · 2.1 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
import java.util.*;
class Queen
{
//number of queens
private static int N;
//chessboard
private static int[][] board = new int[100][100];
//function to check if the cell is attacked or not
private static boolean isAttack(int i,int j)
{
int k,l;
//checking if there is a queen in row or column
for(k=0;k<N;k++)
{
if((board[i][k] == 1) || (board[k][j] == 1))
return true;
}
//checking for diagonals
for(k=0;k<N;k++)
{
for(l=0;l<N;l++)
{
if(((k+l) == (i+j)) || ((k-l) == (i-j)))
{
if(board[k][l] == 1)
return true;
}
}
}
return false;
}
private static boolean nQueen(int n)
{
int i,j;
//if n is 0, solution found
if(n==0)
return true;
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
//checking if we can place a queen here or not
//queen will not be placed if the place is being attacked
//or already occupied
if((!isAttack(i,j)) && (board[i][j]!=1))
{
board[i][j] = 1;
//recursion
//wether we can put the next queen with this arrangment or not
if(nQueen(n-1)==true)
{
return true;
}
board[i][j] = 0;
}
}
}
return false;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
//taking the value of N
System.out.println("Enter the value of N for NxN chessboard");
N = s.nextInt();
int i,j;
//calling the function
nQueen(N);
//printing the matix
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
System.out.print(board[i][j]+"\t");
System.out.print("\n");
}
}
}