package VL05.Aufgabe02; /** * Vorlesung 5 / Aufgabe 2 * * @author Sebastian Brosch */ public class Aufgabe02 { public static void main(String[] args) { final int DAMEN = 8; int chessboard[][] = new int[DAMEN][DAMEN]; queens(chessboard, 1); } /** * Method to place a queen on the chessboard. * * @param chessboard The chessboard to place the queen. * @param q The number of the queen to be placed. */ private static void queens(int[][] chessboard, int q) { if (q > chessboard.length) { print(chessboard); return; } else { for (int i = 0; i < chessboard.length; i++) { if (isQueenPossible(chessboard, q - 1, i)) { chessboard[q - 1][i] = 1; queens(chessboard, q + 1); chessboard[q - 1][i] = 0; } } } } /** * Method to check whether a queen can be placed on the field. * * @param chessboard The chessboard to place the queen. * @param row The row to place the queen. * @param column The column to place the queen. * @return The state whether the queen can be placed on the field. */ private static boolean isQueenPossible(int[][] chessboard, int row, int column) { int currentRow = 0; int currentColumn = 0; // check whether the queen can be placed in current row. for (int c = 0; c < chessboard[row].length; c++) { if (chessboard[row][c] == 1) return false; } // check whether the queen can be placed in current column. for (int r = 0; r < chessboard.length; r++) { if (chessboard[r][column] == 1) return false; } // check whether the queen can be placed diagonal (top left). currentRow = row; currentColumn = column; while (currentColumn >= 0 && currentRow >= 0) { if (chessboard[currentRow][currentColumn] == 1) return false; currentRow--; currentColumn--; } // check whether the queen can be placed diagonal (bottom right). currentRow = row; currentColumn = column; while (currentColumn < chessboard[row].length && currentRow < chessboard.length) { if (chessboard[currentRow][currentColumn] == 1) return false; currentRow++; currentColumn++; } // check whether the queen can be placed diagonal (bottom left). currentRow = row; currentColumn = column; while (currentColumn >= 0 && currentRow < chessboard.length) { if (chessboard[currentRow][currentColumn] == 1) return false; currentRow++; currentColumn--; } // check whether the queen can be placed diagonal (top right). currentRow = row; currentColumn = column; while (currentColumn < chessboard[row].length && currentRow >= 0) { if (chessboard[currentRow][currentColumn] == 1) return false; currentRow--; currentColumn++; } return true; } /** * Method to print a chessboard. * * @param chessboard The chessboard to be printed. */ private static void print(int[][] chessboard) { System.out.println("\nChessboard:\n"); for (int r = 0; r < chessboard.length; r++) { for (int c = 0; c < chessboard[r].length; c++) { System.out.printf("%d", chessboard[r][c]); } System.out.printf("\n"); } } }