public class EightQueen { private int n; private int count; private int[] board; public EightQueen(int n) { this.n = n; count = 0; board = new int[n]; } public void solve() { place(0); if (count == 0) System.out.println("There is no solution."); } private void place(int row) { if (row == n - 1) { for (int i = 0; i < n; i++) { if (!isConflicting(n - 1, i)) { board[n - 1] = i; count++; display(); } } return; } for (int i = 0; i < n; i++) { if (!isConflicting(row, i)) { board[row] = i; place(row + 1); } } } private boolean isConflicting(int row, int col) { for (int i = 0; i < row; i++) { if (board[i] == col || row + col == i + board[i] || row - col == i - board[i]) return true; } return false; } private void display() { System.out.println("solution" + count + ":"); for (int i = 0; i < n; i++) { System.out.print(board[i] + ","); } System.out.println(); } public static void main(String[] args) { //long t1 = System.currentTimeMillis(); new EightQueen(8).solve(); //long t2 = System.currentTimeMillis(); //System.out.println("time:" + (t2 - t1)); } }