Answered step by step
Verified Expert Solution
Question
1 Approved Answer
8. Towers of Hanoi Problem. You are given a set of three poles and n disks, with each disk a different size. Let's name the
8. Towers of Hanoi Problem. You are given a set of three poles and n disks, with each disk a different size. Let's name the poles A, B, and C, and let's number the disks from 1, the smallest disk, to n, the largest disk. At the outset, all n disks are on pole A, in order of decreasing size from bottom to top, so that disk n is on the bottom and disk 1 is on the top. Here's what the Towers of Hanoi looks like for n = 3 disks. Now, the goal is to move all n disks from pole A to pole C by obeying the following two rules: (a) You may move only one disk at a time. (b) No disk may ever rest atop a smaller disk. For example, if disk 1 is on a pole, then all disks below disk 1 must have numbers greater than 1. The following is one runnable java code of "Towers of Hanoi. You can have a try to compile and run it. Now, consider the operation moving one disk from one pole to another" as the basic operation, use the Big O notation to determine its complexity in terms of the input n. Pole A Pole B Pole C III-III Ill-I11 III-III import java.util.Scanner; public class Hanoi { static long count; static void hanoi(int n, char a, char b, char c) if (n==1) // base case System.out.printf ("The d-th movement: \t one disk is moved from pole %c to pole %c ", ++count, a, c); else hanoi (n-1, a, c,b); // recursive call System.out.printf ("The %d-th movement: \t one disk is moved from pole %c to pole %c ", ++count, a, c); hanoi(n-1, b, a,c); // recursive call public static void main(String[] args) { int n; // the number of circles count = 0; System.out.printf ("Towers of Hanoi! "); System.out.printf("Input the number of disks in Towers of Hanoi:"); Scanner input = new Scanner (System.in); n = input.nextInt (); hanoi(n, 'A', 'B', 'C' ); System.out.printf("Done! Total %d movements are needed!", count)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started