漢諾塔的最簡的步驟思路


public class Hanoi{
/**
* 參數說明:
* n:多個盤子
* from:原桿(其上有多個盤子的桿)
* denpend:中間桿
* to:目標桿
*/
public static void hanoi(int n,char from,char denpend,char to){
if(n==1){
System.out.println("將"+n+"號盤子"+from+"---->"+to);
}else{
hanoi(n-1,from,to,denpend);//將N-1盤子從原桿移動到中間桿
System.out.println("將"+n+"號盤子"+from+"---->"+to);//將第N號盤子從原桿移動至目標桿
hanoi(n-1,denpend,from,to);//將N-1盤子從原桿移動到中間桿
}
}

public static void main(String[] args){
char from='A';
char denpend='B';
char to='C';
System.out.println("盤子移動的情況如下:");
hanoi(4,from,denpend,to);//如果4個的情況下
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM