Skip to content

Commit 7af65c8

Browse files
Add implementation for the N-Queens problem using backtracking
1 parent b0c7c09 commit 7af65c8

File tree

1 file changed

+112
-0
lines changed

1 file changed

+112
-0
lines changed

Backtracking/nQueensProblem.java

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
public class nQueensProblem {
2+
public static void main(String[] args) {
3+
int n = 4;
4+
char[][] board = new char[n][n];
5+
6+
for (int i = 0; i < n; i++) {
7+
for (int j = 0; j < n; j++) {
8+
board[i][j] = 'X';
9+
}
10+
11+
}
12+
13+
nqueen(board, 0);
14+
}
15+
16+
static void nqueen(char[][] board, int row) {
17+
int n = board.length;
18+
19+
// base case
20+
if (n == row) {
21+
for (int i = 0; i < n; i++) {
22+
for (int j = 0; j < n; j++) {
23+
System.out.print(board[i][j]);
24+
}
25+
System.out.println();
26+
}
27+
System.out.println();
28+
return;
29+
}
30+
31+
for (int j = 0; j < n; j++) {
32+
33+
if (isSafe(board, row, j)) {
34+
board[row][j] = 'Q';
35+
nqueen(board, row + 1); // resursive callll
36+
board[row][j] = 'X';
37+
38+
}
39+
}
40+
41+
}
42+
43+
static boolean isSafe(char[][] board, int row, int col) {
44+
45+
int n = board.length;
46+
47+
// check row
48+
for (int j = 0; j < n; j++) {
49+
if (board[row][j] == 'Q') {
50+
return false;
51+
}
52+
}
53+
54+
// check coloum
55+
for (int i = 0; i < n; i++) {
56+
if (board[i][col] == 'Q') { // neds to change [i][col]
57+
return false;
58+
}
59+
}
60+
61+
// check right top diagonal
62+
int i = row;
63+
int j = col;
64+
65+
while (i >= 0 && j < n) {
66+
if (board[i][j] == 'Q')
67+
return false;
68+
69+
i--;
70+
j++;
71+
}
72+
73+
// check the right buttom diagonal
74+
i = row;
75+
j = col;
76+
77+
while (i < n && j < n) {
78+
if (board[i][j] == 'Q')
79+
return false;
80+
81+
i++;
82+
j++;
83+
}
84+
85+
// check the left buttom diagonal
86+
87+
i = row;
88+
j = col;
89+
90+
while (i < n && j >= 0) {
91+
if (board[i][j] == 'Q')
92+
return false;
93+
94+
i++;
95+
j--;
96+
}
97+
98+
// check the left top diaonal
99+
i = row;
100+
j = col;
101+
102+
while (i >= 0 && j >= 0) {
103+
if (board[i][j] == 'Q')
104+
return false;
105+
106+
i--;
107+
j--;
108+
}
109+
110+
return true;
111+
}
112+
}

0 commit comments

Comments
 (0)