-
Notifications
You must be signed in to change notification settings - Fork 0
/
nQueenProblem.java
81 lines (69 loc) · 2.32 KB
/
nQueenProblem.java
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public class nQueenProblem {
public static void printSolution(int[][] board, int n)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static boolean isSafe(int[][] board, int row, int column, int n)
{
int i, j;
// Check this row on left side
for (i = 0; i < column; i++)
if (board[row][i] == 1)
return false;
// Check upper diagonal on left side
for (i = row, j = column; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1)
return false;
// Check lower diagonal on left side
for (i = row, j = column; j >= 0 && i < n; i++, j--)
if (board[i][j] == 1)
return false;
return true;
}
//function to solve n Queen problem
static boolean solvenQueen(int board[][], int column, int n)
{
/*
* Base case - if all the queens have got placed then return true
* */
if (column >= n)
{
return true;
}
//consider this column and try placing all the queens one by one in all the rows
for (int i = 0; i < n; i++) {
//check if it is safe to place the queen or not
if (isSafe(board, i, column, n)) {
//place the queen in the board
board[i][column] = 1;
//recursive call for remaining queens
if (solvenQueen(board, column + 1, n) == true) {
return true;
}
//if placing the queen does not lead to solution then backtrack
board[i][column] = 0;
}
}
//if it is not possible to place the queen in any row of the given column then return false
return false;
}
public static void main(String[] args) {
int[][] board = {{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}};
if (solvenQueen(board, 0, board.length) == true) {
printSolution(board, board.length);
}
else {
System.out.print("Solution does not exist");
}
}
}