[转帖] 用C# Generator解决Hanoi塔问题

本文介绍了一种使用C#中的迭代器实现汉诺塔问题的方法,并展示了如何利用递归生成移动步骤。通过枚举和结构体等特性,该实现不仅清晰易懂,还有效地展示了生成器在解决复杂问题上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的代码从[url=http://dotnet.sys-con.com/read/47002.htm]Iterators in C#: Nothing Beats the Foreach Loop[/url]转来。

using System.Collections.Generic;

public enum Peg { A, B, C };

public struct Move {
public Move( Peg from, Peg to ) { From = from; To = to; }
public readonly Peg From;
public readonly Peg To;
}

class TowerofHanoi {
public static IEnumerable<Move> GenerateMoves(
int n, Peg from, Peg to, Peg middle ) {
if ( n == 1 )
yield return new Move( from, to );
else {
foreach ( Move m in GenerateMoves( n - 1, from, middle, to ) )
yield return m;

yield return new Move( from, to );

foreach ( Move m in GenerateMoves( n - 1, middle, to, from ) )
yield return m;
}
}
}

class Program {
static void Main( string[ ] args ) {
foreach ( Move m in
TowerofHanoi.GenerateMoves( 10, Peg.A, Peg.B, Peg.C ) ) {
System.Console.WriteLine( "From {0} to {1}", m.From, m.To );
}
}
}


以前一直没想过generator可以这样用。能让generator自己递归这点相当让我着迷。
最近支持generator的语言也越来越多了。JavaScript也提供了支持。有意思啊……

程序的输出结果放在附件里了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值