This blog will soon be merged with

JavaByPatel

which explains each solution in detail, to visit new blog, click JavaByPatel

Thursday, 1 January 2015

Tower Of Hanoi


package miscellaneous;

/*
 How many moves is required to move a 3 disk from A to B pole
 it is 2^3 - 1 = 7 moves
 so it is 2^n - 1 moves for n disk.     
 */
public class TowersOfHanoi {

 public void solve(int n, String start, String auxiliary, String end) {
  if (n == 1) {
   System.out.println(start + " -> " + end);
  } else {
   solve(n - 1, start, end, auxiliary);
   System.out.println(start + " -> " + end);
   solve(n - 1, auxiliary, start, end);
  }
 }

 public static void main(String[] args) {
  TowersOfHanoi towersOfHanoi = new TowersOfHanoi();
  towersOfHanoi.solve(3, "A", "B", "C");
 }
}

No comments:

Post a Comment