几个比较经典的算法问题的java实现

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 row
14      */
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]) { // 如果该点放了一个皇后,则返回false
44                         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.

 

posted @ 2015-07-13 10:33  夜已殇  阅读(489)  评论(0编辑  收藏  举报