-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNQueen.java
66 lines (58 loc) · 1.85 KB
/
NQueen.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
/*
* FILENAME : NQueen.java
* Problem Statement: Implementation of NQueen's problem
* ------------------------------------------------------------------------------
* AUTHOR : GANESH PAI, Dept. of CS&E, NMAMIT, Nitte
* YEAR : 2021
* E-mail : ganesh.pai@nitte.edu.in
* ------------------------------------------------------------------------------
*/
import java.util.Scanner;
public class NQueen {
private int x[], count = 0, noQ;
private void queen(int k, int n)
{
for(int i = 1; i <= n; i++)
if(place(k, i))
{
x[k] = i;
if(k == n)
printBoard(++count); // Queen Placed in All rows --> Solution
else
queen(k + 1, n);
}
}
private boolean place(int k, int i)
{
for(int m = 1; m <= k-1; m++)
if ( (x[m] == i) || (Math.abs(k - m) == Math.abs(i - x[m])) )//Same column OR diagonal
return false; // Not Placable
return true; // Placable
}
private void printBoard(int cnt)
{
System.out.println("\n Solution " + cnt + "\n");
for(int p = 1; p <= noQ; p++)
{
for(int q = 1; q <= noQ; q++)
System.out.print( (x[p] == q)? "Q " : "- ");
System.out.println();
}
}
public NQueen(int noOfQueens)
{
noQ = noOfQueens;
x = new int[noQ + 1];
}
public void solve()
{
queen(1, noQ);
if (count == 0)
System.out.println("No Solution for " + noQ + "-queens.");
}
public static void main(String[] args) {
System.out.println("Enter the number of Queens:");
int n = new Scanner(System.in).nextInt();
new NQueen(n).solve();
}
}