重新学习C语言的第三天

一、函数的递归
①汉诺塔问题
在这里插入图片描述
将n个盘子从A座移到C座可以分解为以下三个步骤:
(1)将A上n-1个盘借助C座先移到B座上。
(2)把A座上剩下的一个盘移到C座上。
(3)将n-1个盘从B座借助于A座移到C座上。

#include<stdio.h>

int cnt;

int main()
{
	void hanoi(int n,char one,char two,char three);
	int n;
	printf("input the number of diskes:");
	scanf("%d",&n);
	printf("The step to moveing %d diskes:\n",n);
	hanoi(n,'A','B','C');
} 
void hanoi(int n,char one,char two,char three)
{
	void move(char x,char y);
	if(n==1)
	{
		move(one,three);
	}
	else
	{
		hanoi(n-1,one,three,two);
		move(one,three);
		hanoi(n-1,two,one,three);
	}
}
void move(char x,char y)
{
	cnt++;
	printf("step %d: %c--->%c\n",cnt,x,y);
}

在这里插入图片描述

关于递归:要完成最后一步,那么最后一步的前一步要做什么。
在求f(n, other variables)的时候,你就默认f(n -1,other variables)已经被求出来了——至于怎么求的,这个是计算机通过回溯求出来的。( 你把n-1当成一个整体就好了)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章