本帖最后由 我是菜鸟哦 于 2012-8-6 23:19 编辑
今天最后一次学习,用递归实现汉诺塔移动步骤,很简单,原理如下:
1.判断N=1,如果真则打印该移动,然后返回
2.把A上N-1个从A移动到C
3.把N移动到B,然后打印该移动
4.把C上N-1从C移动到B,返回
function HNT(n,src,dst,hlp)
n是数目
src是源头柱子
dst是目的柱子
hlp是辅助柱子
end
用MATLAB实现,小菜技术,大牛路过,睡觉喽。function HNT(n,src,dst,hlp)
if n==1;%%最后一次则打印后结束
disp(['put ' num2str(1) ' from ' src ' to ' dst]);
return;
end
HNT(n-1,src,hlp,dst);
disp(['put ' num2str(n) ' from ' src ' to ' dst]);
HNT(n-1,hlp,dst,src);
end
运行效果如下:HNT(4,'A','B','C');
put 1 from A to C
put 2 from A to B
put 1 from C to B
put 3 from A to C
put 1 from B to A
put 2 from B to C
put 1 from A to C
put 4 from A to B
put 1 from C to B
put 2 from C to A
put 1 from B to A
put 3 from C to B
put 1 from A to C
put 2 from A to B
put 1 from C to B
|