汉诺塔游戏,递归
讲解游戏说明:
有三根柱子,标记为A、B、C,A柱子上有n个大小不同的盘子,盘子从下到上按照大小递增排列。现在需要将A柱子上的所有盘子移动到C柱子上,移动过程中可以借助B柱子,但是每次只能移动一个盘子,并且大盘子不能放在小盘子上面。
起始条件:f(1) = 从A直接移动到C
递归规则:f(n) = 把n-1从A移动到B, 把1从A移动到C, 把n-1从B 移动到C
f(n,a,b,c): 把n个盘子从a移动到c,借助b。
var i =1
def hanoi(n: Int, A: String, B: String,C: String): Unit = {
if (n == 1) {
println(s"$i,move 1 from $A → $C")
} else {
hanoi(n - 1, A, B, C)
println(s"$i,move $n from $A → $C")
i += 1
hanoi(n - 1, B, C, A)
}
}
def main(args: Array[String]): Unit = {
// 4个盘子 从A移动到C,借助B
val n = 4 // 可以修改这个值来改变盘子数量
hanoi(n, "A", "C", "B") // A是源柱子,C是目标柱子,B是辅助柱子
}
输出结果:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C