# 递归方法解决汉诺塔问题（举例说明）

## 递归方法解决汉诺塔问题（举例说明）

from为left, to为mid，num为3. （即从左边移动三个盘子到中间）

move 1 from left to mid
move 2 from left to right
move 1 from mid to right
move 3 from left to mid
move 1 from right to left
move 2 from right to mid
move 1 from left to mid

import java.util.Scanner;
public class HanNuoTa {
public static void main(String[] args) {
Scanner cs = new Scanner(System.in);
System.out.print("盘子个数： ");
int num =cs.nextInt();           //输入盘子个数
System.out.print("起始位置： ");
String from = cs.next();         //输入起始杆，from，mid 或 right
System.out.print("终止位置： ");
String to = cs.next();           //输入目标杆，from，mid 或 right
System.out.println(Pro(num,"left","mid","right",from,to));

}
static int Pro(int num, String left, String mid, String right, String from, String to) {
if(num<1) return 0;
else return process(num,left,mid,right,from,to);
}
static int process(int num, String left, String mid, String right, String from, String to) {
if(num==1) {
System.out.println("move "+ num +" from "+ from +" to "+ to);
return 1;  //返回移动次数
}
//下面为递归体，先要找到除from和to的另一个杆子
//我分为两步去找，如果from和to有一个是mid杆子，则另一个杆子不是left就是right
//否则，另一个杆子就是mid
//然后开始移动
if(from.equals(mid)||to.equals(mid)) {
String another = (from.equals(left)||to.equals(left))?right:left;
//找到另一个杆子another
int part1 = process(num-1,left,mid,right,from,another);
//将num-1个圆盘从from移到another
int part2 = 1;
System.out.println("move "+ num +" from "+ from +" to "+ mid);
//将剩余一个最大的圆盘num移到to
int part3 = process(num-1,left,mid,right,another,to);
//最后将num-1个圆盘从another移到to
return part1+part2+part3;  //返回移动次数
}
else {
//此时另一个圆盘就是mid
int part1 = process(num-1,left,mid,right,from,mid);
int part2 = 1;
System.out.println("move "+ num +" from "+ from +" to "+ to);
int part3 = process(num-1,left,mid,right,mid,to);
return part1+part2+part3;
}
}
}

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客