0

## 遞歸(漢諾塔)問題？

<script language="javascript">
var hanoi = function (disc, src, aux, dst){
if (disc > 0) {
hanoi(disc-1, src, dst, aux);
document.write('Move disc ' + disc +' from ' + src + ' to ' + dst+'<br>');
hanoi(disc-1, aux, src, dst);
}
}
hanoi(3, 'Src', 'Aux', 'Dst');
</SCRIPT>

Move disc 1 from Src to Dst
Move disc 2 from Src to Aux
Move disc 1 from Dst to Aux
Move disc 3 from Src to Dst
Move disc 1 from Aux to Src
Move disc 2 from Aux to Dst
Move disc 1 from Src to Dst

fillano iT邦超人 1 級 ‧ 2010-05-03 11:51:17 檢舉

### 2 個回答

18
fillano
iT邦超人 1 級 ‧ 2010-04-27 09:54:59

hungchinwai iT邦研究生 1 級 ‧ 2010-04-27 11:00:25 檢舉

``````&lt;pre class="c" name="code">
&lt;HTML>
&lt;script language="javascript">
var cnt=0;
var hanoi = function (disc, src, aux, dst){
document.write(++cnt + '.' + 'calling hanoi disc:' + disc + ' from:' + src + ' to:' + dst + ' &lt;/br>');
if (disc > 0) {
hanoi(disc-1, src, dst, aux);
document.write(++cnt + '.' + '-----Move disc ' + disc +' from ' + src + ' to ' + dst+'&lt;br>');
hanoi(disc-1, aux, src, dst);
}
}
hanoi(3, 'Src', 'Aux', 'Dst');
&lt;/SCRIPT>
&lt;/HTML>
``````
``````&lt;pre class="c" name="code">

1.calling hanoi disc:3 from:Src to:Dst
2.calling hanoi disc:2 from:Src to:Aux
3.calling hanoi disc:1 from:Src to:Dst
4.calling hanoi disc:0 from:Src to:Aux
5.-----Move disc 1 from Src to Dst
6.calling hanoi disc:0 from:Aux to:Dst
7.-----Move disc 2 from Src to Aux
8.calling hanoi disc:1 from:Dst to:Aux
9.calling hanoi disc:0 from:Dst to:Src
10.-----Move disc 1 from Dst to Aux
11.calling hanoi disc:0 from:Src to:Aux
12.-----Move disc 3 from Src to Dst
13.calling hanoi disc:2 from:Aux to:Dst
14.calling hanoi disc:1 from:Aux to:Src
15.calling hanoi disc:0 from:Aux to:Dst
16.-----Move disc 1 from Aux to Src
17.calling hanoi disc:0 from:Dst to:Src
18.-----Move disc 2 from Aux to Dst
19.calling hanoi disc:1 from:Src to:Dst
20.calling hanoi disc:0 from:Src to:Aux
21.-----Move disc 1 from Src to Dst
22.calling hanoi disc:0 from:Aux to:Dst
``````
fillano iT邦超人 1 級 ‧ 2010-04-27 14:59:06 檢舉

``````&lt;pre class="c" name="code">
&lt;script language="javascript">
var depth = 0;
var hanoi = function (disc, src, aux, dst){
depth++;
if (disc > 0) {
hanoi(disc-1, src, dst, aux);
document.write('depth:'+depth+', Move disc ' + disc +' from ' + src + ' to ' + dst+'&lt;br>');
hanoi(disc-1, aux, src, dst);
}
depth--;
}
hanoi(3, 'Src', 'Aux', 'Dst');
&lt;/script>
``````
shunyuan iT邦研究生 1 級 ‧ 2010-04-28 02:50:14 檢舉

hungchinwai iT邦研究生 1 級 ‧ 2010-04-30 17:57:23 檢舉

n>0時,f(n)是f(n-1)及一列'Move..'及f(n-1)
n=0時,f(n)什麼事都不做

hanoi(3)=(2-11)(12)(13-22)
hanoi(2)=(3-6)(7)(8-11)
hanoi(1)=(4-6)
hanoi(1)=(9-11)
hanoi(2)=(14-17)(18)(19-22)
hanoi(1)=(15-17)
hanoi(1)=(20-22)

8
marshuang
iT邦新手 1 級 ‧ 2010-04-27 09:06:22