Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to solve towers of hanoi problem?

public class TowersOfHanoi {
	/*
	 * This code solves the towers of Hanoi problem
	 * The considered puzzle consists of three pegs
	 * and a set of rings. Each ring has a different
	 * size. Initially all rings are stacked on leftmost
	 * peg in ascending order of size.
	 * Aim: move all rings from leftmost peg to destination
	 * peg while obeying following rules: 1) Only one ring
	 * can be moved at a time; 2) A larger ring cannot
	 * be placed on top of a smaller one.
	 * Let n be the number of rings.
	 * 
	 * Time complexity: O(2^n)
	 * Space complexity: O(n)
	 */
	public static void main(String[] args) {
		int nbDisks = 3;
		moveTower(nbDisks, 1, 3, 2);
		/*
		 * The above prints:
		 * 1->3
		 * 1->2
		 * 3->2
		 * 1->3
		 * 2->1
		 * 2->3
		 * 1->3
		 */
	}

	// Method for moving n disks from start to end via extra
	private static void moveTower(int n, int start, int end, int extra) {
		// Base case of 0 disks
		if (n == 0)
			return;
		// Move n-1 disks out of the way
		moveTower(n - 1, start, extra, end);
		moveOneDisk(start, end);
		// Move remaining n-1 disks to destination
		moveTower(n - 1, extra, end, start);
	}

	private static void moveOneDisk(int start, int end) {
		System.out.println(start + "->" + end);
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: java selenium new empty window 
Java :: java how to get current date 
Java :: request permission foreground service 
Java :: bucket sort java 
Java :: gradle springboot run 
Java :: java lerp 
Java :: spigot spawn entity 
Java :: how can I split string according to space in java? 
Java :: java print treemap 
Java :: max long 
Java :: generate random string in java 
Java :: android hide soft keyboard 
Java :: java check ipv6 with regex 
Java :: send message to all player java spigot 
Java :: bukkit runnable 
Java :: java calculate fps 
Java :: bubble sort java 
Java :: check if string contains numbers 
Java :: android studio allow http 
Java :: java for schleife 
Java :: system.out.println 
Java :: stackoverflow spring regex 
Java :: k combinations for range 1 through n 
Java :: jbutton actionlistener 
Java :: android how to start a new activity on button click 
Java :: how to change orientation of linearlayout in recyclerview android 
Java :: comment out and uncomment in netbeans java 
Java :: android java date from internet 
Java :: show confirmation dialog java android 
Java :: Date from String java3 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =