N-Queens
Mon Nov 18 2024 12:15:59 GMT+0000 (Coordinated Universal Time)
Saved by
@badram123
import java.util.Scanner;
public class NQueens {
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] == 1 ? "Q " : ". "));
}
System.out.println();
}
System.out.println();
}
static boolean isSafe(int[][] board, int row, int col, int n) {
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;
}
static boolean solveNQueens(int[][] board, int row, int n) {
if (row == n) {
printSolution(board, n);
return true;
}
boolean result = false;
for (int col = 0; col < n; col++) {
if (isSafe(board, row, col, n)) {
board[row][col] = 1;
result = solveNQueens(board, row + 1, n) || result;
board[row][col] = 0;
}
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of N: ");
int n = sc.nextInt();
int[][] board = new int[n][n];
System.out.println("Solutions to the " + n + "-Queens problem:");
if (!solveNQueens(board, 0, n)) {
System.out.println("No solution exists.");
}
}
}
content_copyCOPY
Comments