public class NQueens {
private static final int N = 4;
public static void main(String[] args) {
solveNQueens();
}
private static void solveNQueens() {
int[][] board = new int[N][N];
if (!solveNQueensUtil(board, 0)) {
System.out.println("There is no solution");
}
}
private static boolean solveNQueensUtil(int[][] board, int row) {
if (row == N) {
printSolution(board);
return true;
}
boolean res = false;
for (int i = 0; i < N; i++) {
if (isSafe(board, row, i)) {
board[row][i] = 1;
res = solveNQueensUtil(board, row + 1) || res;
board[row][i] = 0;
}
}
return res;
}
private static boolean isSafe(int[][] board, int row, int col) {
for (int i = 0; i < row; i++) {
if (board[i][col] == 1) {
return false;
}
}
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1) {
return false;
}
}
for (int i = row, j = col; i >= 0 && j < N; i--, j++) {
if (board[i][j] == 1) {
return false;
}
}
return true;
}
private static void printSolution(int[][] board) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
}