nqueens
import java.util.ArrayList;
import java.util.List;
public class NQueens {
public static List<List<String>> solveNQueens(int n) {
List<List<String>> solutions = new ArrayList<>();
char[][] board = new char[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = '.';
}
}
placeQueens(solutions, board, 0, n);
return solutions;
}
private static void placeQueens(List<List<String>> solutions, char[][] board, int row, int n) {
if (row == n) {
solutions.add(constructSolution(board));
return;
}
for (int col = 0; col < n; col++) {
if (isSafe(board, row, col, n)) {
board[row][col] = 'Q'; // Place a queen
placeQueens(solutions, board, row + 1, n); // Recur for the next row
board[row][col] = '.'; // Backtrack
}
}
}
private static boolean isSafe(char[][] board, int row, int col, int n) {
for (int i = 0; i < row; i++) {
if (board[i][col] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (board[i][j] == 'Q') {
return false;
}
}
return true;
}
private static List<String> constructSolution(char[][] board) {
List<String> solution = new ArrayList<>();
for (char[] row : board) {
solution.add(new String(row));
}
return solution;
}
// Main function
public static void main(String[] args) {
int n = 8; // Change the value of n as needed
List<List<String>> solutions = solveNQueens(n);
System.out.println("Total Solutions for " + n + "-Queens: " + solutions.size());
for (List<String> solution : solutions) {
for (String row : solution) {
System.out.println(row);
}
System.out.println();
}
}
}
Comments
Post a Comment