標籤:
1.八皇后問題
1 public class EightQueen { 2 3 private static final int ROW = 16; 4 private static final int COL = 16; 5 6 private static int count = 0; // 八皇后的解的個數 7 8 private static boolean[][] maps = new boolean[ROW][COL]; // 初始化二維數組,類比8*8棋盤,預設值是false表示沒有皇后 9 10 // 如何去放皇后?11 /**12 * 防止第row行的皇后13 * @param row14 */15 public static void putQueen(int row) {16 17 // 遞迴的出口18 if (row == ROW) { // row=8時,已經到了第9行,那麼前面的8行就是OK的19 printQueen();20 return;21 }22 23 // 把皇后放到第row行的第j列24 for (int j = 0; j < COL; j++) {25 // 如果可以放,就將皇后放在該點26 if (isOK(row, j)) {27 maps[row][j] = true;28 putQueen(row + 1); // 該行放好之後放下一行【遞迴去放皇后】,演算法已經跳轉29 maps[row][j] = false; // 回溯,當放row+1行棋子不滿足的時候,會回溯到第row行30 }31 }32 }33 34 // 如果要將皇后放在(x,y)點,則需要先判斷該點是否可以放35 public static boolean isOK(int x, int y) {36 37 // 遍曆二維數組,判斷4個方向是否存在皇后38 for (int i = 0; i < ROW; i++) {39 for (int j = 0; j < COL; j++) {40 // 正斜邊x-y定值,逆斜邊x+y為定值41 if (i == x || j == y || i - j == x - y || i + j == x + y) {42 // 判斷4個方向是否存在皇后43 if (maps[i][j]) { // 如果該點放了一個皇后,則返回false44 return false;45 }46 }47 }48 }49 50 return true;51 }52 53 public static void printQueen() {54 55 System.out.println("第" + (++count) + "個解");56 System.out.println("*******************");57 for (int i = 0; i < ROW; i++) {58 for (int j = 0; j < COL; j++) {59 if (maps[i][j]) {60 System.out.print("Q ");61 } else {62 System.out.print("* ");63 }64 }65 System.out.println();66 }67 }68 69 public static void main(String[] args) {70 71 putQueen(0);72 }73 }2.豆機(梅花瓶,高爾頓瓶問題)3.
幾個比較經典的演算法問題的java實現