-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathNQueen.java
More file actions
65 lines (53 loc) · 1.4 KB
/
NQueen.java
File metadata and controls
65 lines (53 loc) · 1.4 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
public class NQueen {
static void show(boolean board[][]) {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board.length; j++) {
if(board[i][j]) {
System.out.println(i + "," + j);
}
}
}
}
static int getCount(boolean board[][], int currentRow) {
int count = 0;
// Positive Base Case
if(currentRow == board.length) {
show(board);
return 1;
}
for(int col = 0; col < board[currentRow].length; col++) {
if(isSafeArea(board, currentRow, col)) {
board[currentRow][col] = true;
count = count + getCount(board, currentRow+1);
// backtracking
board[currentRow][col] = false;
}
}
return count;
}
static boolean isSafeArea(boolean[][] board, int row, int col) {
// check if queen is available in same column
for(int i = row; i >= 0; i--) {
if(board[i][col]) {
return false;
}
}
// check if queen is available in upper left diagonal
for(int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if(board[i][j]) {
return false;
}
}
// check if queen is available in upper right diagonal
for(int i = row, j = col; i >= 0 && j < board.length; i--, j++) {
if(board[i][j]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
boolean [][]board = new boolean[4][4];
System.out.println(getCount(board,0));
}
}