重新學習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當成一個整體就好了)

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