递归方法----汉诺塔问题

递归思想解决 汉诺塔问题

1
package Recursive; 2 3 public class TestHanoi { 4 public static void main(String[] args) { 5 hanoi(3,'A','B','C'); 6 } 7 8 /** 9 * 10 * @param n 共有N个盘子 11 * @param from 开始的柱子 12 * @param in 中间的柱子 13 * @param to 目标柱子 14 */ 15 public static void hanoi(int n,char from,char in,char to){ 16 if(n==1){ 17 System.out.println("第一个盘子从"+from+"移到"+to); 18 19 }else{ 20 //移动上面所有的盘子到中间位置 21 hanoi(n-1,from,to,in); 22 //移动下面的盘子 23 System.out.println("第"+n+"个盘子从"+from+"移到"+to); 24 //把上面的所有盘子从中间位置移到目标位置 25 hanoi(n-1,in,from,to); 26 } 27 28 } 29 30 }

猜你喜欢

转载自www.cnblogs.com/axu521/p/9972141.html
今日推荐