public class EightQueen { private int index = 1; private final static int SCALE = 8; private int[] answer = new int[SCALE]; private void initArray() { for (int i = 0; i < answer.length; i++) { answer[i] = -1; } } private boolean canStay(int row, int col) { for (int i = 0; i < row; i++) { if (answer[i] == col || Math.abs(row - i) == Math.abs(col - answer[i])) { return false; } } return true; } private void calculate() { for (int row = 0; row < SCALE; row++) { if (answer[row] == -1) { answer[row] = 0; } for (int col = answer[row]; col <= SCALE; col++) { if (col == SCALE) { answer[row] = -1; row--; if (row < 0) { return; } col = answer[row]; continue; } if (canStay(row, col)) { answer[row] = col; if (row == SCALE - 1) { showmsg(); continue; } break; } } } } private void showmsg() { if (index<4) { System.out.println(" - 第" + index + "种方案 -"); for (int i = 0; i < answer.length; i++) { for (int j = 0; j < SCALE; j++) { if (answer[i] == j) { System.out.print("Q "); } else { System.out.print("X "); } } System.out.println(""); } System.out.println("\n"); index++; } } public EightQueen() { initArray(); calculate(); } public static void main(String[] args) { System.out.println("列举"+SCALE+"皇后问题的前 3 种方案!"); System.out.println(); EightQueen eightQueen = new EightQueen(); } }
第一次实验,八皇后问题
最新推荐文章于 2022-12-16 21:22:35 发布