C# program to Towers of Hanoi using recursion
Here's a C# program that solves the Towers of Hanoi problem using recursion:
using System;
class Program
{
static void Main()
{
int numberOfDisks = 3;
char source = 'A';
char auxiliary = 'B';
char destination = 'C';
Console.WriteLine("Towers of Hanoi Steps:");
SolveTowersOfHanoi(numberOfDisks, source, auxiliary, destination);
}
static void SolveTowersOfHanoi(int n, char source, char auxiliary, char destination)
{
if (n == 1)
{
Console.WriteLine($"Move disk 1 from {source} to {destination}");
return;
}
SolveTowersOfHanoi(n - 1, source, destination, auxiliary);
Console.WriteLine($"Move disk {n} from {source} to {destination}");
SolveTowersOfHanoi(n - 1, auxiliary, source, destination);
}
}
In this program, we have the SolveTowersOfHanoi method that solves the Towers of Hanoi problem. It takes the number of disks (n), the source tower (source), auxiliary tower (auxiliary), and the destination tower (destination) as parameters.
The base case of the recursion is when n is equal to 1. In this case, it directly moves the disk from the source tower to the destination tower and prints the step.
In the recursive case, it follows the steps of the Towers of Hanoi problem. It first recursively calls SolveTowersOfHanoi with n - 1 disks, moving them from the source tower to the auxiliary tower using the destination tower as the auxiliary. Then, it moves the largest disk (disk n) from the source tower to the destination tower and prints the step. Finally, it recursively calls SolveTowersOfHanoi again with n - 1 disks, moving them from the auxiliary tower to the destination tower using the source tower as the auxiliary.
The Main method initializes the number of disks (3) and the labels for the source (A), auxiliary (B), and destination (C) towers. It calls the SolveTowersOfHanoi method to solve the Towers of Hanoi problem with the given parameters. The program prints the steps involved in moving the disks from the source tower to the destination tower.
In the example above, the output would be:
Towers of Hanoi Steps:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
These are the steps required to solve the Towers of Hanoi problem with 3 disks.