Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Java: Tower of Hanoi
/** * Tower of Hanoi * * @author Jayesh Chandrapal * @version: 1.0 */ import java.util.*; import java.lang.*; class Rextester { /** * Main program entry point * How to execute: >java Rextester */ public static void main(String args[]) { TowerOfHanoi app = new TowerOfHanoi(); // app.solve(TOTAL_DISKS, from_pole, to_pole, helper_pole); app.solve(TOTAL_DISKS, 1, 3, 2); System.out.println("Done in " + count + " steps"); } } class TowerOfHanoi { static int count = 0; List<Stack<Integer>> poles; private static final int TOTAL_POLES = 3; private static final int TOTAL_DISKS = 4; TowerOfHanoi() { poles = new ArrayList<Stack<Integer>>(); for(int i = 0; i < TOTAL_POLES; i++) { poles.add(new Stack<Integer>()); } for(int i = TOTAL_DISKS; i > 0; i--) { poles.get(0).push(i); } System.out.println(poles); } public void solve(int disks, int from, int to, int helper) { if(disks >= 1) { count++; solve(disks - 1, from, helper, to); System.out.println(); System.out.println("Moving Disk" + poles.get(from - 1).peek() + " from " + from + " to " + to); poles.get(to - 1).push(poles.get(from - 1).pop()); System.out.println("[Poles: " + poles + "]"); solve(disks - 1, helper, to, from); } } }
run
|
edit
|
history
|
help
0
ContainsMethod
bit right 2
3e
4c
Palindrome Number in Java
HelloUser
Quadratic equation
Day 2
Sieve of Eratosthenes Revisited
javaLP