Skip to content

Commit 22742a9

Browse files
committed
counts total possible way to place N Queens in NXN board, backtracking, recursion
1 parent b073a97 commit 22742a9

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package Lecture12;
2+
3+
public class NQueen {
4+
5+
public static void main(String[] args) {
6+
7+
int N = 4;
8+
boolean[][] board = new boolean[N][N];
9+
int row = 0;
10+
System.out.println(countNQueens(board, row)); // 2
11+
}
12+
13+
public static int countNQueens(boolean[][] board, int row) {
14+
if (row == board.length) {
15+
return 1;
16+
}
17+
18+
int count = 0;
19+
for (int col = 0; col < board.length; col++) {
20+
if (isSafePosition(board, row, col)) {
21+
board[row][col] = true;
22+
count = count + countNQueens(board, row + 1);
23+
board[row][col] = false;
24+
}
25+
}
26+
return count;
27+
}
28+
29+
public static boolean isSafePosition(boolean[][] board, int row, int col) {
30+
// checking column
31+
for (int i = row; i >= 0; i--) {
32+
if (board[i][col]) {
33+
return false;
34+
}
35+
}
36+
37+
// checking left diagonal
38+
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
39+
if (board[i][j]) {
40+
return false;
41+
}
42+
}
43+
44+
// checking right diagonal
45+
for (int i = row, j = col; i >= 0 && j < board.length; i--, j++) {
46+
if (board[i][j]) {
47+
return false;
48+
}
49+
}
50+
51+
return true;
52+
}
53+
54+
/*
55+
public static void display(boolean[][] board) {
56+
for (int row = 0; row < board.length; row++) {
57+
for (int col = 0; col < board[row].length; col++) {
58+
System.out.print(board[row][col] + " ");
59+
}
60+
System.out.println();
61+
}
62+
}
63+
*/
64+
65+
}

0 commit comments

Comments
 (0)