1. 程式人生 > >棧實現遞歸實現漢諾塔問題

棧實現遞歸實現漢諾塔問題

漢諾塔 遞歸實現 char else noi spa java pre demo

 1 public class JavaDemo {
 2     private int c = 0;
 3 
 4     public static void main(String[] args) {
 5         JavaDemo demo = new JavaDemo();
 6         demo.hanoi(3, ‘x‘, ‘y‘, ‘z‘);
 7     }
 8     
 9     public void hanoi(int n, char x, char y, char z){
10     if(n == 1){
11         move(x, 1, z);
12 }else{ 13 hanoi(n - 1, x, z, y); 14 move(x, n, z); 15 hanoi(n - 1, y, x, z); 16 } 17 } 18 19 public void move(char x, int n, char z){ 20 System.out.println("第" + ++c + "次移動:" + n + "號圓盤," + x + "->" + z); 21 } 22 }

棧實現遞歸實現漢諾塔問題