递归实现汉诺塔问题:
package com.threetop.www;
/**
* 递归解汉诺塔问题
* @author wjgs
*
*/
public class HanoiTest {
public static void hanoi(int n,char A,char B,char C)
{
if(n==1)
{
move(A,C);
return;
}
//递归调用 将A上的n-1圆盘移动到B上
hanoi(n-1,A,C,B);
move(A,C);
hanoi(n-1,B,A,C);
}
/**
* 将A最后面的圆盘移动到C上去
* @param A
* @param C
*/
private static void move(char A, char C) {
// TODO Auto-generated method stub
System.out.println(A+"-->"+C);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
hanoi(3,'A','B','C');
}
}
输出结果如下:
转载请注明原文地址: https://ju.6miu.com/read-676080.html