package algs; /** * Author: areful * Date: 2018/8/9 */ public class Queen8 { private static final int MAX_QUEEN = 8; private int[] cols = new int[MAX_QUEEN]; private int num = 0; private void calc() { getArrangement(0); System.out.println(MAX_QUEEN + "皇后问题有" + num + "种摆放方法。"); } private void getArrangement(int n) { boolean[] rows = new boolean[MAX_QUEEN]; for (int i = 0; i < n; i++) { rows[cols[i]] = true; int d = n - i; if (cols[i] - d >= 0) rows[cols[i] - d] = true; if (cols[i] + d <= MAX_QUEEN - 1) rows[cols[i] + d] = true; } for (int i = 0; i < MAX_QUEEN; i++) { if (rows[i]) continue; cols[n] = i; if (n < MAX_QUEEN - 1) { getArrangement(n + 1); } else { num++; printChessBoard(); } } } private void printChessBoard() { System.out.println("第" + num + "种走法"); for (int i = 0; i < MAX_QUEEN; i++) { for (int j = 0; j < MAX_QUEEN; j++) { if (i == cols[j]) { System.out.print("0 "); } else System.out.print(". "); } System.out.println(); } } public static void main(String[] args) { new Queen8().calc(); } }