幾個比較經典的演算法問題的java實現

來源:互聯網
上載者:User

標籤:

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實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.