-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueen.java
More file actions
56 lines (49 loc) · 1.71 KB
/
Copy pathNQueen.java
File metadata and controls
56 lines (49 loc) · 1.71 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
package Backtracking.Day_10;
public class NQueen {
static int countWays(boolean [][]board, int currentRow) {
int count = 0;
// add base case to check if we are out of the board
if(currentRow == board.length) {
return 1;
}
// Traverse all columns of board
for(int col = 0; col < board[currentRow].length; col++) {
// check if queen is safe to place
if(isSafe(board, currentRow, col)) {
// place the queen on board
board[currentRow][col] = true;
// move to the next row once a queen is place in current row
count += countWays(board, currentRow + 1);
// this is the backtracking
board[currentRow][col] = false;
}
}
return count;
}
static boolean isSafe(boolean board[][], int row, int col) {
// check if there is a queen in same column and above row
for(int i = row; i>= 0; i--) {
if(board[i][col]) {
return false;
}
}
// check in upper left diagonal
for(int i = row, j = col; i >= 0 && j >= 0; i--,j--) {
if(board[i][j]) {
return false;
}
}
// check 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];
int count = countWays(board, 0);
System.out.println(count);
}
}