hanoi包含三步
- 把 n-1 号盘子移动到缓冲区
- 把1号从起点移到终点
- 然后把缓冲区的n-1号盘子也移到终点
所以写成py代码就是:
def hanoi(n,x,y,z):
if n==1:
print(x,'-->',z)
else:
hanoi(n-1,x,z,y) #将前n-1个盘子从x移动到y上
hanoi(1,x,y,z) #将最底下的最后一个盘子从x移动到z上
hanoi(n-1,y,x,z) #将y上的n-1个盘子移动到z上
n=int(input('请输入汉诺塔的层数:'))
hanoi(n,'x','y','z')
- 要从a到b 那c就是缓冲 move(n-1,from,to,buffer)
- 要从a到c 那b就是缓冲 move(1,from,buffer,to)
- 要从b到c 那a就是缓冲 move(n-1,buffer,from,to)
所以写成java代码就是:
package test;
public class Hanoi {
public void hanoi(int n, char origin, char assist, char destination) {
if (n == 1) {
move(origin, destination);
} else {
hanoi(n - 1, origin, destination, assist);
move(origin, destination);
hanoi(n - 1, assist, origin, destination);
}
}
// Print the route of the movement
private void move(char origin, char destination) {
System.out.println("Direction:" + origin + "--->" + destination);
}
public static void main(String[] args) {
Hanoi hanoi = new Hanoi();
hanoi.hanoi(3, 'A', 'B', 'C');
}
}