-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNQueens.java
85 lines (69 loc) · 1.68 KB
/
NQueens.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
package DAA_Practicals;
public class NQueens {
public static void main(String[] args) {
int n=8;
int board[][]=new int[n][n];
System.out.println("The solution for "+n+" queens is : ");
solve(0,n,board);
}
private static void solve(int col, int n, int[][] board) {
if(col==n)
{
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(" " + board[i][j]);
}
System.out.println();
}
System.out.println();
return;
}
for(int row=0;row<n;row++)
{
if(issafe(col,row,n,board))
{
board[row][col]=1;
solve(col+1, n, board);
board[row][col]=0;
}
}
}
private static boolean issafe(int col, int row, int n,int[][] board) {
int x=row;
int y=col;
while(y>=0)
{
if(board[x][y]==1)
return false;
y--;
}
y=col;
while (x >= 0 && y >= 0) // check for upper diagonal
{
if (board[x][y] == 1)
return false;
y--;
x--;
}
x = row;
y = col;
while (x < n && y >= 0) // check for lower diagonal
{
if (board[x][y] == 1)
return false;
y--;
x++;
}
return true;
}
}
// Output:
// The solution for 4 queens is :
// 0 0 1 0
// 1 0 0 0
// 0 0 0 1
// 0 1 0 0
// 0 1 0 0
// 0 0 0 1
// 1 0 0 0
// 0 0 1 0