public class AllNQueenPosibility {
int size;
int k = 1;
public AllNQueenPosibility(int n) {
this.size = n;
}
/// this method will print the result matrix
void printNQueen(int[][] board) {
System.out.println("\n" + k++ +"\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
// this is the first method to solve, in this will create matrix of size and then pass it to another method to get result
private void solveNQ() {
int[][] board = new int[size][size];
if (!solveNQUtil(board, 0)) {
System.out.println("solution dsnt exist");
return;
}
return;
}
// this method is used to set the correct position of queen in matrix
private boolean solveNQUtil(int[][] board, int col) {
if (col == size) {
printNQueen(board);
return true;
}
boolean res = false;
for (int i = 0; i < size; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
res = solveNQUtil(board, col + 1) || res;
board[i][col] = 0;
}
}
return res;
}
// this method is used to verify correct position of queen in matrix , this will use recursive call to find correct location
private boolean isSafe(int[][] board, int row, int col) {
for (int i = 0; i < col; i++) {
if (board[row][i] == 1) {
return false;
}
}
for (int i = row, j = col; j >= 0 && i >= 0; j--, i--) {
if (board[i][j] == 1)
return false;
}
for (int i = row, j = col; i < size && j >= 0; i++, j--) {
if (board[i][j] == 1)
return false;
}
return true;
}
public static void main(String[] args) {
AllNQueenPosibility all = new AllNQueenPosibility(4);
all.solveNQ();
}
}