C# 实现汉诺塔编程问题 – 码农在线

C# 实现汉诺塔编程问题

 

实现汉诺塔的思想很简单,即用递归,所谓递归,简单理解,就是自己调用自己的方法,实现循环,直至完成为止。下面看代码:

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace hanno{ class Program { static void hanoi(int n, char A, char B, char C) { if (n == 1) Console.WriteLine("move disc {0} from {1} to {2}", n, A, C); else { hanoi(n - 1, A, C, B); Console.WriteLine("move disc {0} from {1} to {2}", n, A, C); hanoi(n - 1, B, A, C); } } static void Main(string[] args) { int n; Console.WriteLine("input n: \n"); n = Convert.ToInt32(Console.ReadLine()); hanoi( n, 'A', 'B', 'C'); Console.ReadKey(); } }}