Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * When the height is 3, the output is<br/>
- * "A -> B<br/>
- * A -> C<br/>
- * B -> C<br/>
- * A -> B<br/>
- * C -> A<br/>
- * C -> B<br/>
- * A -> B".
- */
- public class Hanoi {
- private final int height;
- private final String tower1;
- private final String tower2;
- private final String tower3;
- public Hanoi(final int height,
- final String tower1,
- final String tower2,
- final String tower3) {
- this.height = height;
- this.tower1 = tower1;
- this.tower2 = tower2;
- this.tower3 = tower3;
- }
- public Hanoi(int height) {
- this(height, "A", "B", "C");
- }
- public void execute() {
- moveDisc(height, tower1, tower2, tower3);
- }
- private void moveDisc(final int disk,
- final String source,
- final String dest,
- final String aux) {
- if (disk == 1) {
- System.out.println(String.format("%s -> %s", source, dest));
- }
- else {
- moveDisc(disk - 1, source, aux, dest);
- System.out.println(String.format("%s -> %s", source, dest));
- moveDisc(disk - 1, aux, dest, source);
- }
- }
- }
Add Comment
Please, Sign In to add comment