Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to solve the towers of Hanoi Java?

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 :: change visibility of textview andoird 
Java :: how to validate email java 
Java :: android coding how to open map 
Java :: transparent dialog in android 
Java :: Could not find any matches for com.transistorsoft:tsbackgroundfetch:+ as no versions of com.transistorsoft:tsbackgroundfetch are available. 
Java :: generate random letters and numbers in java 
Java :: spigot run task later 
Java :: Failed to resolve org.junit.platform:junit-platform-launcher:1.7.0 
Java :: keyset sort java 
Java :: show dialog fragment from adapter 
Java :: random string method java 
Java :: apk full form 
Java :: java stream sorted reverse 
Java :: Howow to use font object Java 
Java :: java yesterday date 
Java :: java how to calculate fps 
Java :: remove last character from string java 
Java :: for loop in multidimensional array java 
Java :: java import decimalformat 
Java :: java take screenshot 
Java :: bundletool aab to apk 
Java :: display default value of auto commit java 
Java :: java ee schedule every 10 seconds 
Java :: default night mode not working 
Java :: java Date get today date 
Java :: brxm remove property 
Java :: React-Native Firebase Requests from referer are blocked 
Java :: How to efficiently find the middle node of a singly linked list without counting its nodes, in Java? 
Java :: get id of html tag by class 
Java :: date from string java 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =