Skip to content

Commit d4fe20a

Browse files
authored
n-queens problem
1 parent d6c7ffd commit d4fe20a

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

NQueenProblem.java

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
2+
public class NQueenProblem {
3+
final int N = 4;
4+
5+
6+
void printSolution(int board[][])
7+
{
8+
for (int i = 0; i < N; i++) {
9+
for (int j = 0; j < N; j++)
10+
System.out.print(" " + board[i][j]
11+
+ " ");
12+
System.out.println();
13+
}
14+
}
15+
16+
17+
boolean isSafe(int board[][], int row, int col)
18+
{
19+
int i, j;
20+
21+
22+
for (i = 0; i < col; i++)
23+
if (board[row][i] == 1)
24+
return false;
25+
26+
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
27+
if (board[i][j] == 1)
28+
return false;
29+
30+
for (i = row, j = col; j >= 0 && i < N; i++, j--)
31+
if (board[i][j] == 1)
32+
return false;
33+
34+
return true;
35+
}
36+
37+
boolean solveNQUtil(int board[][], int col)
38+
{
39+
40+
if (col >= N)
41+
return true;
42+
43+
for (int i = 0; i < N; i++) {
44+
if (isSafe(board, i, col)) {
45+
board[i][col] = 1;
46+
if (solveNQUtil(board, col + 1) == true)
47+
return true;
48+
49+
board[i][col] = 0;
50+
}
51+
}
52+
return false;
53+
}
54+
55+
boolean solveNQ()
56+
{
57+
int board[][] = { { 0, 0, 0, 0 },
58+
{ 0, 0, 0, 0 },
59+
{ 0, 0, 0, 0 },
60+
{ 0, 0, 0, 0 } };
61+
62+
if (solveNQUtil(board, 0) == false) {
63+
System.out.print("Solution does not exist");
64+
return false;
65+
}
66+
67+
printSolution(board);
68+
return true;
69+
}
70+
71+
public static void main(String args[])
72+
{
73+
NQueenProblem Queen = new NQueenProblem();
74+
Queen.solveNQ();
75+
}
76+
}

0 commit comments

Comments
 (0)