Java开发网 |
注册 |
登录 |
帮助 |
搜索 |
排行榜 |
发帖统计
|
您没有登录 |
» Java开发网 » Java SE 综合讨论区
打印话题 寄给朋友 订阅主题 |
作者 | 向高手请教一个汉诺塔的问题 |
lucent6688
发贴: 1 积分: 0 |
于 2005-04-17 22:56
被这个汉诺塔的源程序搞得头痛,好心的高手能告诉我如何理解这个汉诺塔吗 能告诉我其中的规律性吗? 小弟在此先谢了! // Lab 3: TowersOfHanoi.java // Program solves the Towers of Hanoi problem import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TowersOfHanoi extends JApplet implements ActionListener { JLabel label; JTextField input; JTextArea outputArea; String output; public void init() { output = ""; // create components label = new JLabel( "Enter number of disks ( 1-9 ): " ); input = new JTextField( 5 ); input.addActionListener( this ); outputArea = new JTextArea( 15, 20 ); /* Write code that creates a JScrollPane and attach outputArea to it */ // outputArea.setText( output ); JScrollPane scroll = new JScrollPane(outputArea); // add components to applet Container container = getContentPane(); container.setLayout( new FlowLayout() ); /* Write code to add the components to the content pane */ input.addActionListener(this); container.add(label); container.add(input); container.add(scroll); } // recusively move disks through towers /* write header for method tower */ String tower(int n,String peg1,String peg2,String peg3) { /* Write code here that tests for the base case (i.e., one disk). In this case, move the last disk from peg 1 to peg 3 and return. */ if(n==1) return output+="\n"+peg1+"--->"+peg3; // move ( disks - 1 ) disks from peg1 to peg2 recursively /* Write a recursive call to method tower that moves ( disks - 1 ) disks from peg1 to peg2 */ else { tower(n-1,peg1,peg3,peg2); // move last disk from peg1 to peg3 recursively output += "\n" + peg1 + " --> " + peg3; // move ( disks - 1 ) disks from peg2 to peg3 recursively /* Write a recursive call to method tower that moves ( disks - 1 ) disks from peg2 to peg3 */ tower(n-1,peg2,peg1,peg3); return output; } } // actually sort the number of discs specified by user public void actionPerformed( ActionEvent e ) { output = ""; /* call method tower and pass it the number input by the user, a starting peg of 1, an ending peg of 3 and a temporary peg of 2 */ int n=Integer.parseInt(input.getText()); String peg1="1"; String peg2="2"; String peg3="3"; output+=tower(n,peg1,peg2,peg3); outputArea.setText( output ); } } // end class TowersOfHanoi 当n=2时,监听器内调用tower(n,peg1,peg2,peg3)方法,当运行至tower(n-1,peg1,peg3,peg2)时,也就是tower(1,peg1,peg3,peg2);再次调用自身方法,这时就运行if(n==1) return output+="\n"+peg1+"--->"+peg3; 也就是返回output=1-->2给调用者,程序也就结束了,可实际的答案是 1-->2,1-->3, 2-->3 应如何理解?各位大侠能帮个忙吗? 为什么这个Applet不能在浏览器显示啊? |
话题树型展开 |
人气 | 标题 | 作者 | 字数 | 发贴时间 |
3926 | 向高手请教一个汉诺塔的问题 | lucent6688 | 2907 | 2005-04-17 22:56 |
3057 | Re:向高手请教一个汉诺塔的问题 | Yach | 136 | 2005-04-19 23:20 |
已读帖子 新的帖子 被删除的帖子 |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |