[Java] Java递归 汉诺塔的递归 →→→→→进入此内容的聊天室

来自 , 2021-04-23, 写在 Java, 查看 147 次.
URL http://www.code666.cn/view/d93ed5b6
  1. package algorithm.recursion;
  2. public class HanoiTower{
  3.     private static int step= 0;  
  4.     /**汉诺塔的递归演示。
  5.      * @param from  碟子的出发地
  6.      * @param temp  碟子的中转站
  7.      * @param to   碟子的到达地
  8.      * @param n  要移动的碟子个数
  9.      */
  10.     static void  hanoi(char from, char temp, char to, int n){
  11.         if (n == 1) {
  12.            step++;
  13.            System.out.println("第"+step+ "步: "+ from+"→"+ to);
  14.         }else {
  15.             //将n-1个碟子移到中转站,故目前的到达地是temp。
  16.             hanoi(from, to,temp,n-1);
  17.             //第n个碟子移到到达地
  18.             step++;
  19.             System.out.println("第"+step+ "步: "+ from+"→"+ to);
  20.             //将n-1个碟子移到到达地。
  21.             hanoi(temp,from,to,n-1);
  22.         }
  23.     }
  24. }

回复 "Java递归 汉诺塔的递归"

这儿你可以回复上面这条便签

captcha