public class EightQueens {
// Method to print the board with the solution
static void printBoard(int board[][], int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1) {
System.out.print("Q "); // Q represents a queen
} else {
System.out.print(". "); // . represents an empty space
}
}
System.out.println();
}
}
// Method to check if a queen can be placed at board[row][col]
static boolean isSafe(int board[][], int row, int col, int N) {
// Check the column for previous rows
for (int i = 0; i < row; i++) {
if (board[i][col] == 1) {
return false;
}
}
// Check the upper-left diagonal
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1) {
return false;
}
}
// Check the upper-right diagonal
for (int i = row, j = col; i >= 0 && j < N; i--, j++) {
if (board[i][j] == 1) {
return false;
}
}
return true;
}
// Backtracking function to solve the problem
static boolean solveEightQueens(int board[][], int row, int N) {
if (row == N) {
// All queens are placed
return true;
}
// Try placing a queen in each column one by one
for (int col = 0; col < N; col++) {
if (isSafe(board, row, col, N)) {
board[row][col] = 1; // Place queen
// Recur to place the next queen
if (solveEightQueens(board, row + 1, N)) {
return true;
}
// If placing queen in board[row][col] doesn't work, backtrack
board[row][col] = 0;
}
}
return false; // If no place is found for a queen in this row
}
public static void main(String[] args) {
int N = 8; // Size of the board (8x8 for the 8-Queens problem)
int[][] board = new int[N][N];
if (!solveEightQueens(board, 0, N)) {
System.out.println("Solution does not exist");
} else {
printBoard(board, N);
}
}
}