算法的一些小栗子10(回溯算法)

来源:互联网 发布:支付宝怎么绑定淘宝 编辑:程序博客网 时间:2024/05/21 10:46

回溯算法

//回溯算法八皇后public class Queen {    public static int num = 0;//累计方案    public static final int MAXQUEEN = 8;    public static int[] cols = new int[MAXQUEEN];//定义cols数组,表示8列棋子摆放的位置    public void getCount(int n) {        boolean[] rows = new boolean[MAXQUEEN];//记录每列每个方格是否可以放皇后        for (int m = 0; m < n; m++) {            rows[cols[m]] = true;            int d = n - m;//斜对角            //正斜方向            if (cols[m] - d > 0) {                rows[cols[m] - d] = true;            }            //反斜方向            if (cols[m] + d <= (MAXQUEEN - 1)) {                rows[cols[m] + d] = true;            }        }        //到此知道了哪些位置不能放皇后        for (int i = 0; i < MAXQUEEN; i++) {            if (rows[i]) {                //不能放                continue;            }            cols[n] = i;            //下面可能仍然有合法位置            if (n < MAXQUEEN - 1) {                getCount(n + 1);            } else {                //找到了完整的一套方案                num++;                printQueen();            }        }    }    private void printQueen() {        System.out.println("第" + num + "种方案:");        for (int i = 0; i < MAXQUEEN; i++) {            for (int j = 0; j < MAXQUEEN; j++) {                if (i == cols[j]) {                    System.out.print("0 ");                } else {                    System.out.print("+ ");                }            }            System.out.println();        }    }    public static void main(String[] args) {        Queen queen = new Queen();        queen.getCount(0);    }}

杀人法

//回溯算法public class Josephus {    public static int N = 20;    public static int M = 5;//数到M就杀掉    class Node {        int val;//下标        Node next;        public Node(int val) {            this.val = val;        }    }    public void killNode() {        Node header = new Node(1);//第一个节点        Node x = header;//目前被点到的人        for (int i = 2; i <= N; i++) {            x = (x.next = new Node(i));        }        x.next = header;//头尾相接        System.out.println("被杀掉的顺序为:");        while (x != x.next) {            //仍然还有两人,仍然报数杀掉            for (int i = 1; i < M; i++) {                x = x.next;            }            System.out.println(x.next.val + "被杀掉");            x.next = x.next.next;        }        System.out.println("最后的幸存者是:" + x.val);    }    public static void main(String[] args) {        Josephus josephus = new Josephus();        josephus.killNode();    }}