import java.util.*; public class NQueens { public static void solveNQueens(int n) { int[] board = new int[n]; Arrays.fill(board, -1); solve(0, board, n); } private static void solve(int col, int[] board, int n) { if (col == n) { printBoard(board, n); return; } for (int row = 0; row < n; row++) { if (isSafe(board, col, row, n)) { board[col] = row; solve(col + 1, board, n); board[col] = -1; } } } private static boolean isSafe(int[] board, int col, int row, int n) { for (int i = 0; i < col; i++) { if (board[i] == row || Math.abs(board[i] - row) == Math.abs(i - col)) { return false; } } return true; } private static void printBoard(int[] board, int n) { for (int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < n; j++) { sb.append(board[i] == j ? 'Q' : '.'); } System.out.println(sb.toString()); } System.out.println(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the value of n (size of the board): "); int n = scanner.nextInt(); solveNQueens(n); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter