【java算法】汉诺塔问题求解

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Hanoi {
	public static void main(String[] args) throws NumberFormatException, IOException{
		int n;
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("请输入棋盘数");
		n = Integer.parseInt(buf.readLine());
		Hanoi hanoi = new Hanoi();
		hanoi.move(n,'A','B','C');
	}
	//A位首柱,B为中柱,C为尾柱
	public void move(int n,char a,char b,char c){
		if(n==1){
			System.out.println("盘"+n+":"+a+"-->"+c);
		}else{
			//将n-1个柱子从首柱移到中柱,中柱为辅助塔
			move(n-1,a,c,b);
			System.out.println("盘"+n+":"+a+"-->"+c);
			//将n-1个柱子从中柱移动尾柱,首柱为辅助塔
			move(n-1,b,a,c);
		}
	}
}

你可能感兴趣的:(java算法)