package hanoi; /** * Hanoi塔问题 * @author Administrator * */ /* * (1)通过解决其他问题来解决原始问题 * (2)其他问题比原始问题小;需要移动的圆盘少。准确的讲,每次递归调用使圆盘个数减1. * (3)当问题只有一个圆盘时(即基例),可直接得到解 * (4)这种使问题不断减小的方式确保最终达到基例 */ public class Hanoi { public void solveTowers(int cout,char source,char destination,char spare){ if(cout == 1){ System.out.println("Move top disk from pole "+source+" " +"to pole "+destination); } else{ //1:忽略底部的最大圆盘,将上面的n-1圆盘从标杆A移到标杆C,把标杆B看作为空余标杆; solveTowers(cout-1,source,spare,destination); //2:把最大圆盘从标杆A处移到标杆B; solveTowers(1,source,destination,spare); //3:把n-1个圆盘从标杆C移到标杆B,将A用作空余标杆。 solveTowers(cout-1,spare,destination,source); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Hanoi hanoi = new Hanoi(); hanoi.solveTowers(4, 'a', 'b', 'c'); } }