Last active
April 10, 2016 05:20
-
-
Save srajappa/b31f27e0d1bdac2080aa3b5d3ef895dd to your computer and use it in GitHub Desktop.
Program that shows the steps to solve a problem of Tower of Hanoi.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Hanoi{ | |
public static void towerOfHanoi(int numberOfRings){ | |
//final int NUM_OF_PEGS=3; | |
List<Deque<Integer>> pegs = new ArrayList<>(); | |
for(int i=0; i<NUM_OF_PEGS; i++){ | |
pegs.add(new LinkedList()); | |
} | |
//Initialize the first Peg | |
for(int i=numberOfRings; i>=1; i--){ | |
pegs.get(0).addFirst(i); | |
} | |
hanoiHelper(numberOfRings, pegs, 0, 2, 1); | |
} | |
public static void hanoiHelper(int numOfRings, List<Deque<Integer>> pegs, int source, int dest, int intermed){ | |
if(numOfRings>0){ | |
hanoiHelper(numOfRings-1, pegs, source, intermed, dest); | |
pegs.get(dest).addFirst(pegs.get(source).removeFirst()); | |
System.out.println("Move from PEG#"+source+" Dest #"+dest); | |
hanoiHelper(numOfRings-1,pegs, intermed, dest, source); | |
} | |
} | |
public static void main(String[] args){ | |
int numOfRings=4; | |
towerOfHanoi(numOfRings); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment