Advertisement
Guest User

Towers of Hanoi

a guest
Apr 24th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class run{
  5.     public static void main(String[] args) throws FileNotFoundException,IOException{
  6.         //String to file
  7.         String file = "Prob15.in.txt";
  8.         //New BufferedReader object
  9.         BufferedReader br = new BufferedReader(new FileReader(file));
  10.         //Acquire test cases
  11.         int testCases = Integer.parseInt(br.readLine());
  12.         //Loop through test cases
  13.         while(testCases-- > 0){
  14.             //Read disk amount
  15.             int n = Integer.parseInt(br.readLine());
  16.             //Print out amount of disks in stack
  17.             System.out.println(n);
  18.             //Solve towers
  19.             solveTowers(n, "A", "B", "C");
  20.         }
  21.     }
  22.     public static void printMove(String from, String to){
  23.         System.out.println(from + "->" + to);
  24.     }
  25.     public static void solveTowers(int n, String from, String spare, String to){
  26.         if(n == 1){
  27.             printMove(from, to);
  28.         }else{
  29.             solveTowers(n - 1, from, to, spare);
  30.             printMove(from, to);
  31.             solveTowers(n - 1, spare, from, to);
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement