算法——汉诺塔

2022-3-2 diaba 算法

package com.jiucaiyuan.question;

/**
 * 汉诺塔
 * <p>
 * Created by jiucaiyuan on 2022/2/4.
 */
public class HannuoTower {
    public static void main(String[] args) {
        hannuoTower(16);
    }
    public static void hannuoTower(int n) {
        if (n > 0) {
            moveTower(n, "左", "右", "中");
        }
    }
    /**
     * @param i 有几个盘子需要移动
     * @param from  这几个盘子所在的位置
     * @param to    这几个盘子要移动到的目标位置
     * @param mid   临时位置
     */
    public static void moveTower(int i, String from, String to, String mid) {
        if (i == 1) {
            System.out.println("move " + i + " " + from + " ——> " + to);
            return;
        }
        moveTower(i - 1, from, mid, to);
        System.out.println("move " + i + " " + from + " ——> " + to);
        moveTower(i - 1, mid, to, from);
    }
}

标签: 算法 汉诺塔 递归

发表评论:

Powered by emlog 京ICP备15045175号-1 Copyright © 2022