Towers of Hanoi 递归和构建 java 走地牙 CTCI 8.6

本文深入探讨了经典的汉诺塔问题,详细解析其递归算法,并提供了使用Stacks进行盘子移动的Java代码实现。通过具体的编程示例,展示了如何遵循汉诺塔的三大规则,将盘子从第一个塔移动到最后一个塔。

Towers of Hanoi: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:

(1) Only one disk can be moved at a time.

(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.
Write a program to move the disks from the first tower to the last using Stacks.

 

/*

汉诺塔的递归;
思路: 利用递归求解是 出口时n == 1时 从a--》c;
                      正常的步骤 无论有多少层都是要把除了最后一层的所有盘子先挪到b,然后再把最后一层挪到c ,最后才把之前b上的所有盘子挪到c,
*/
public class Solution {
    /**
     * @param n: the number of disks
     * @return: the order of moves
     */
    public List<String> towerOfHanoi(int n) {
        // write your code here
        List<String> result = new ArrayList<String>();
        if(n == 0) return result;
        helper(result, n, 'A', 'B', 'C');
        return result;
    }
    
    public void helper(List<String> result, int n, char a, char b, char c) {
        if(n == 1) {
            result.add("from " + a +" to " + c);
            return;
        }
        helper(result, n - 1, a, c, b);
        result.add("from " + a + " to " + c);
        helper(result, n - 1, b, a, c);
    }
}

汉诺塔的构建

public class Tower {
    private Stack<Integer> disks;
    private int index;
    /*
    * @param i: An integer from 0 to 2
    */
    public Tower(int i) {
        // create three towers
        disks = new Stack<Integer>();
        index = i;
    }

    /*
     * @param d: An integer
     * @return: nothing
     */
    public int getIndex () {
        return index;
    }
    
    public void add(int d) {
        // Add a disk into this tower
        if (!disks.isEmpty() && disks.peek() <= d) {
            System.out.println("Error placing disk " + d);
        } else {
            disks.push(d);
        }
    }

    /*
     * @param t: a tower
     * @return: nothing
     */
    public void moveTopTo(Tower t) {
        // Move the top disk of this tower to the top of t.
        int temp = disks.pop();
        t.add(temp);
    }

    /*
     * @param n: An integer
     * @param destination: a tower
     * @param buffer: a tower
     * @return: nothing
     */
    public void moveDisks(int n, Tower destination, Tower buffer) {
        // Move n Disks from this tower to destination by buffer tower
        if(n > 0) {
            moveDisks(n - 1, buffer, destination);
            moveTopTo(destination);
            buffer.moveDisks(n - 1, destination, this);
        }
    }

    /*
     * @return: Disks
     */
    public Stack<Integer> getDisks() {
        // write your code here
        return disks;
    }
}

/**
 * Your Tower object will be instantiated and called as such:
 * Tower[] towers = new Tower[3];   
 * for (int i = 0; i < 3; i++) towers[i] = new Tower(i);
 * for (int i = n - 1; i >= 0; i--) towers[0].add(i);   
 * towers[0].moveDisks(n, towers[2], towers[1]);
 * print towers[0], towers[1], towers[2]
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值