The queen's problem is usually solved by 2 functions of <10 lines each:
public static boolean isSolution(final int[] board) { for (int i = 0; i < board.length; i++) { for (int j = i + 1; j < board.length; j++) { if (board[i] == board[j]) return false; // same column "|" if (board[i]-board[j] == i-j) return false; // diagonal "\" if (board[i]-board[j] == j-i) return false; // diagonal "/" } } return true; }
public static void solve(int depth, int[] board) { if (depth == board.length && isSolution(board)) { outputSolution(board); } if (depth < board.length) { // try all positions of the next row for (int i = 0; i < board.length; i++) { board[depth] = i; solve(depth + 1, board); } } }
public static void outputSolution(final int[] board) { System.out.println("--- Solution ---"); for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i]; j++) { System.out.print(" "); } System.out.println("Q"); } }
public static void main(String[] args) { int n = 8; solve(0, new int[n]); }
|