Select the appropriate code for the recursive Tower of Hanoi problem.(n is the number of disks)

Select the appropriate code for the recursive Tower of Hanoi problem.(n is the number of disks)
A.
Code:
public void solve(int n, String start, String auxiliary, String end)
{
       if (n == 1) 
       {
           System.out.println(start + " -> " + end);
       } 
       else
       {
           solve(n - 1, start, end, auxiliary);
           System.out.println(start + " -> " + end);
           solve(n - 1, auxiliary, start, end);
       }
}
B.
Code:
public void solve(int n, String start, String auxiliary, String end) 
{
       if (n == 1) 
       {
           System.out.println(start + " -> " + end);
       } 
       else 
       {
           solve(n - 1, auxiliary, start, end);
           System.out.println(start + " -> " + end);
       }
}
C.
Code:
public void solve(int n, String start, String auxiliary, String end) 
{
       if (n == 1) 
       {
           System.out.println(start + " -> " + end);
       } 
       else 
       {
           System.out.println(start + " -> " + end);
	   solve(n - 1, auxiliary, start, end);
       }
}
D.
Code:
public void solve(int n, String start, String auxiliary, String end)
{
       if (n == 1) 
       {
           System.out.println(start + " -> " + end);
       } 
       else
       {
           solve(n - 1, start, end, auxiliary);
           System.out.println(start + " -> " + end);
       }
}
 
Answer: A
Explanation: First transfer all the diska to the auxiliary and then to the end peg, this is achieved by making auxiliary peg as the end peg in the first recursive call, in the second recursive call, the auxiliary becomes the start peg from where the disks are transferred to the end peg.
 

Tìm kiếm

Back
Top