汉诺塔问题OpenJudge2.2基本算法之递归和自调用函数

好的写法在这,有描述思路

#include<iostream>
using namespace std;
int n;
char a,b,c;
void hanno(int x,char ori,char mid,char des)
{
    if(x==0) return;
    hanno(x-1,ori,des,mid);
    cout<<ori<<"->"<<x<<"->"<<des<<endl;
    hanno(x-1,mid,ori,des);
}
int main()
{
    cin>>n>>a>>b>>c;
    hanno(n,a,c,b);
}

对初学者来说,很难写出这样的代码,因为这里涉及了函数的参数怎么设置的问题。

思路;现在你要写一个函数,能把x个盘子从起始杆子移到目标杆子。

必须要先把x-1个盘子移到到中间那个杆子,这就是一个子问题,写成代码就是

hanno(x-1,ori,des,mid)。好,现在你实现了把x-1个盘子移到中间的杆子,就可以把在ori上的第x个盘子移到到des上,就输出一下。

现在你只需要把mid上的x-1个盘子移到des上就大功告成了,写成代码就是hanno(x-1,mid,ori,des)

最后注意一下递归终止条件 x==0 返回

分割线------------------------------------------------------------------------------------------------------------------------

不会递归、不会根据当前的目标去巧妙设置函数参数的时候 写出来破代码

​
​
​这是一个多月前写的,第一次接触汉诺塔,根本不会从子问题,规模变小这些角度
去思考问题。就通过写出n比较小的时候的答案,在观察答案中找到了规律。
当时正好学了链表,感觉这题可以用。就写出了这么个现在自己都不能立即看不懂的代码。
#include<iostream>
#include<cstring>
using namespace std;
struct node
{
	char pole;
	node * next;
};
node * creatList(node * head1, char a, char b, char c)
{
	head1 = new node;
	head1->pole = a;
	node * r1 = NULL;
	r1 = new node;
	head1->next = r1;
	r1->pole = c;
	r1 = new node;
	head1->next->next = r1;
	r1->pole = b;
	r1->next = head1;
	return head1;
}
void Func(int n, int m,node * head1[],node * head2[])
{
	if (n == 1)
	{
		if (m % 2 == 0)
		{
			printf("%c->%d->%c\n", head1[n]->pole, n, head1[n]->next->pole);
			head1[n] = head1[n]->next;
		}
		else
		{
			printf("%c->%d->%c\n", head2[n]->pole, n, head2[n]->next->pole);
			head2[n] = head2[n]->next;
		}
		return;
	}
	Func(n - 1, m, head1, head2);
	if ((m-n)%2==0)
	{
		printf("%c->%d->%c\n", head2[n]->pole, n, head2[n]->next->pole);
		head2[n] = head2[n]->next;
	}
	else
	{
		printf("%c->%d->%c\n", head1[n]->pole, n, head1[n]->next->pole);
		head1[n] = head1[n]->next;
	}
	Func(n - 1, m, head1, head2);
}
int main()
{
	int n;
	cin >> n;
	char a, b, c;
	cin >> a >> b >> c;
	node * head1 = NULL, * head2 = NULL;
	head1 = creatList(head1, a, b, c);
	head2 = creatList(head2, a, c, b);
	node * p1[64];
	node * p2[64];
	for (int i = 1;i <= n;i++)
	{
		p1[i] = head1;
		p2[i] = head2;
	}
	Func(n, n, p1, p2);
}

​

​

​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值