德国开元华人社区 开元周游
标题:
汗诺塔的堆栈实现,挺经典
[打印本页]
作者:
brett
时间:
22.9.2003 03:03
提示:
作者被禁止或删除 内容自动屏蔽
作者:
gm_jwl
时间:
22.9.2003 17:40
<!--QuoteBegin--></span><table border='0' align='center' width='95%' cellpadding='3' cellspacing='1'><tr><td><b>QUOTE</b> </td></tr><tr><td id='QUOTE'><!--QuoteEBegin-->stack.push(new Quad(n-1,y,x,z));<br>stack.push(new Quad(1,x,y,z));<br>stack.push(new Quad(n-1,x,z,y));<br><!--QuoteEnd--></td></tr></table><span class='postcolor'><!--QuoteEEnd--><br>这里有误,应当是:<br><span style='color:blue'>stack.push(new Quad(n-1,x,z,y));<br>stack.push(new Quad(1,x,y,z));<br>stack.push(new Quad(n-1,y,x,z));</span><br>次序不能颠倒的,我想。
作者:
gm_jwl
时间:
22.9.2003 17:49
用递归的方法,两种可以比较一下。<br>public class Hanoi{<br>public static void main(String[] args)<br>{ hanoi(3,'A','B','C'); // play the game with 3 disks<br>}<br>private int step=0;<br>void prt(int n,int from,int to){<br>System.out.println("Step "+(++step)+" move "+n+" from stab "+from+" to "+to);<br>}<br>public static void hanoi(int n,int from,int extra,int to){<br>if(n==1) prt(1,from,to);<br>else{ hanoi(n-1,from,to,extra);<br>prt(n,from ,to);<br>hanoi(n-1,extra,from,to);<br>}<br>return;<br>}<br>}
作者:
brett
时间:
22.9.2003 22:18
提示:
作者被禁止或删除 内容自动屏蔽
作者:
gm_jwl
时间:
23.9.2003 13:54
啊,是啊,我都忘了。 <!--emo&(y)--><img src='https://www.kaiyuan.info/modules/ipboard/html/emoticons/thumbs_up.gif' border='0' style='vertical-align:middle' alt='thumbs_up.gif'><!--endemo-->
作者:
woo
时间:
24.9.2003 23:30
我们当年是用scheme实现的,忘了是怎么写的了,好像挺复杂,不过rekursive的问题本身就很复杂<br>
作者:
gm_jwl
时间:
26.9.2003 16:01
用SCHEME语言来实现:<br><br>(define (hanoi n from extra to)<br> (define (prt n from to) <br> (begin (display "move ")<br> (display n)<br> (display " from ")<br> (display from)<br> (display " to ")<br> (display to)<br> ))<br> (define (hanoi-rek n from extra to)<br> (if (= n 1) (prt 1 from to) <br> (begin (hanoi-rek (- n 1) from to extra)<br> (prt n from to)<br> (hanoi-rek (- n 1) extra from to)<br> )<br> ))<br>)<br> <br>
欢迎光临 德国开元华人社区 开元周游 (https://forum.kaiyuan.cn/)
Powered by Discuz! X3.2