下面的代码居然是错误的,您把n=1;n=2带入都不ok,如何修改对?

plglenn35 2009-12-23 10:27:43
修改
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HanoiProgram
{
class Program
{
static long count = 0;
static void move(char x, char y)
{
Console.WriteLine("{0}--->{1}", x, y);
}
static void hanoi(int n, char one, char two, char three)
{
if (n == 1)
{
count += 2;
move(one, two);
move(two, three);
}
else
{
count += 2;
hanoi(n - 1, one, two, three);
move(one, two);
hanoi(n - 1, three, two, one);
move(two, three);
hanoi(n - 1, one, two, three);
}
}
static void Main(string[] args)
{
Console.WriteLine("需要搬几个盘子");
int n = int.Parse(Console.ReadLine());
hanoi(n, 'A', 'B', 'C');
Console.WriteLine("搬迁结速;一共进行了{0}次的搬迁。", count);
Console.Read();
}

}
}
...全文
68 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
silentwins 2009-12-23
  • 打赏
  • 举报
回复
第一:count += 2; 肯定是错的,没道理+2的,应该+1

第二:
hanoi(n - 1, one, two, three);
move(one, two);
hanoi(n - 1, three, two, one);
move(two, three);
hanoi(n - 1, one, two, three);

这里调用了3次hanoi,明显也是有问题的,貌似第一、二步很多余,删掉答案是对的,再仔细研究一下逻辑
HarveyYan 2009-12-23
  • 打赏
  • 举报
回复

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HanoiProgram
{
class Program
{
static long count = 0;
static void move(char x, char y)
{
count += 1;
Console.WriteLine("{0}--->{1}", x, y);
}
static void hanoi(int n, char one, char two, char three)
{
if (n == 1)
{

move(one, two);
move(two, three);
}
else
{
hanoi(n - 1, one, two, three);
move(one, two);
hanoi(n - 1, three, two, one);
move(two, three);
hanoi(n - 1, one, two, three);
}
}
static void Main(string[] args)
{
Console.WriteLine("需要搬几个盘子");
int n = int.Parse(Console.ReadLine());
hanoi(n, 'A', 'B', 'C');
Console.WriteLine("搬迁结速;一共进行了{0}次的搬迁。", count);
Console.Read();
}

}
}

wuyq11 2009-12-23
  • 打赏
  • 举报
回复
static void Hanoi(int n,char one, char two,char three)
{
if (n == 1)
{
++count;
PrintMove(one, three);
}
else
{
++count;
Hanoi(n-1,one,three,two);
PrintMove(one,three);
Hanoi(n-1,two,one,three);

}
silentwins 2009-12-23
  • 打赏
  • 举报
回复
测试好像可用,有什么问题?

不过貌似答案是错误的...

62,264

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧