C# Tower of Hanoi: Recursive Solution

The Tower of Hanoi problem is a classic recursion problem that can be solved using recursive algorithms. Below is an example of a recursive algorithm for solving the Tower of Hanoi problem written in C#.

using System;

class MainClass {
    public static void Main (string[] args) {
        int n = 3; // 汉诺塔的盘子数量
        Hanoi(n, 'A', 'B', 'C');
    }

    // 递归函数,将n个盘子从A经过B移动到C
    static void Hanoi(int n, char source, char auxiliary, char target) {
        if (n == 1) {
            Console.WriteLine($"移动盘子 {n}{source}{target}");
        } else {
            Hanoi(n - 1, source, target, auxiliary);
            Console.WriteLine($"移动盘子 {n}{source}{target}");
            Hanoi(n - 1, auxiliary, source, target);
        }
    }
}

In the example above, we defined a Hanoi function that takes three parameters: the number of disks n, the source pillar, the auxiliary pillar, and the target pillar. We then use recursive calls to solve the Towers of Hanoi problem.

You can set the number of disks for the Tower of Hanoi in the Main function, and then call the Hanoi function to print out the steps for moving each disk.

bannerAds