Skip to content

Commit 273a4a9

Browse files
committed
#Modification 13
1 parent 10ab7fa commit 273a4a9

1 file changed

Lines changed: 86 additions & 0 deletions

File tree

backtracking/N_Queen.java

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package backtracking;
2+
3+
public class N_Queen {
4+
final int N = 4;
5+
6+
void printSolution(int board[][]) {
7+
for (int i = 0; i < N; i++) {
8+
for (int j = 0; j < N; j++) {
9+
System.out.print(" " + board[i][j] + " ");
10+
System.out.println();
11+
}
12+
}
13+
}
14+
15+
boolean isSafe(int board[][], int row, int col) {
16+
int i, j;
17+
18+
for (i = 0; i < col; i++) {
19+
if (board[row][i] == 1)
20+
return false;
21+
}
22+
23+
for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
24+
if (board[i][j] == 1) {
25+
return false;
26+
}
27+
}
28+
29+
for (i = row, j = col; j >= 0 && i < N; i++, j--) {
30+
if (board[i][j] == 1)
31+
return false;
32+
}
33+
34+
return true;
35+
}
36+
37+
boolean solveNQUtil(int board[][], int col) {
38+
if (col >= N)
39+
return true;
40+
41+
for (int i = 0; i < N; i++) {
42+
if (isSafe(board, i, col)) {
43+
board[i][col] = 1;
44+
45+
if (solveNQUtil(board, col + 1) == true)
46+
return true;
47+
48+
/*
49+
If placing queen in board[i][col] doesn't lead to a solution then rempve queen from board[i][col]
50+
*/
51+
board[i][col] = 0; //"BACKTRACK"
52+
}
53+
}
54+
55+
/*
56+
* If the queen can not be palced in any row in this col, then return false
57+
*/
58+
return false;
59+
}
60+
61+
/*
62+
* This function solves the N-Queen problem using "BACKTRACKING".
63+
* It mainly uses solveNQUtil() to solve the problem.
64+
* It return false if queens cannot placed, otherwise,
65+
* return true & prints placement of queens in the form of 1's.
66+
* Please note that there may be more than one solutions,
67+
* this functionprints one of the feasible solutions.
68+
*/
69+
boolean solveNQ() {
70+
int board[][] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };
71+
72+
if (solveNQUtil(board, 0) == false) {
73+
System.out.println("Solution does not exist");
74+
return false;
75+
}
76+
77+
printSolution(board);
78+
return true;
79+
}
80+
81+
//Driver program to test above functions
82+
public static void main(String[] args) {
83+
N_Queen nq = new N_Queen();
84+
nq.solveNQ();
85+
}
86+
}

0 commit comments

Comments
 (0)