-
Notifications
You must be signed in to change notification settings - Fork 0
/
NQueenAlgo.java
85 lines (83 loc) · 1.31 KB
/
NQueenAlgo.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
import java.util.*;
/*Contributed by (Vinit Korade)*/
public class NQueenAlgo
{
int no;
int placed[], matrix[][];
public Scanner sc = new Scanner(System.in);
public NQueenAlgo()
{
System.out.print("Enter N:- ");
no = sc.nextInt();
placed = new int[no];
matrix = new int[no][no];
for(int i=0;i<no;i++)
{
placed[i]=-1;
}
initBoard();
algo(0,no);
}
public void initBoard()
{
for(int i=0;i<no;i++)
{
for(int j=0;j<no;j++)
{
matrix[i][j]=0;
}
}
}
public void algo(int k, int n )
{
for(int i=0;i<n;i++)
{
if (place(k,i))
{
placed[k] = i;
if(k==(n-1))
{
System.out.println();
show();
}
else
{
algo(k+1,n);
}
}
}
}
public boolean place(int k, int i)
{
for(int j=0;j<k;j++)
{
if(placed[j]==i || Math.abs(placed[j]-i)==Math.abs(j-k) )
{
return false;
}
}
return true;
}
public void show()
{
System.out.println();
for(int i=0;i<no;i++)
{
System.out.print("\t"+placed[i]);
}
for(int i=0;i<no;i++)
{
System.out.println();
for(int j=0;j<no;j++)
{
if(j==placed[i])
{
matrix[i][j]=1;
}
System.out.print("\t"+matrix[i][j]);
}
}
initBoard();
}
}
/*Contributed by (Wincore)*/