双色Hanoi塔问题-递归
思想:1-将n-1个圆盘从A移动到C,B为辅助
2-将第n个圆盘从A移动到B,C为辅助
3-将n-1个圆盘从C移动到B,A为辅助
方式1:键盘输入,控制台输出。
import java.util.Scanner;
public class Hanoi {
public static void hanoi(int n, String from, String to, String helper){
if(n == 1){ //递归出口,就1个圆盘
System.out.println(n + " " + from + " " + to);
return ;
}
hanoi(n-1, from, helper, to) ; //将n-1个圆盘从A移动到C,B为辅助
System.out.println(n + " " + from + " " + to); //将第n个圆盘从A移动到B
hanoi(n-1, helper, to, from) ; //将n-1个圆盘从C移动到B,A为辅助
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in) ;
int n = input.nextInt() ;
hanoi(n, "A", "B", "C") ;
}
}
方式2:文件流输入输出。
import java.io.*;
public class Hanoi1 {
public static String line ;
public static int n ;
public static String [] array = new String [10000];
public static int i = 0 ;
public static void hanoi(int n, String from, String to, String helper) throws IOException {
if(n == 1){ //递归出口,就1个圆盘
array[i++] = n + " " + from + " " + to ;
return ;
}
hanoi(n-1, from, helper, to) ; //将n-1个圆盘从A移动到C,B为辅助
array[i++] = n + " " + from + " " + to ;
hanoi(n-1, helper, to, from) ; //将n-1个圆盘从C移动到B,A为辅助
}
public static void main(String[] args) {
try (FileInputStream input = new FileInputStream("D:\\study\\input.txt");
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(input))){
line = dataInputStream.readLine() ;
n = Integer.parseInt(line) ;
hanoi(n, "A", "B", "C") ;
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
try ( FileOutputStream output = new FileOutputStream("D:\\study\\output.txt");
DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(output))){
for(int j=0; j<array.length; j++) {
if(array[j] != null)
dataOutputStream.writeBytes(array[j] + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}