且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

汇编汉诺塔

更新时间:2022-06-03 00:30:56

 1 .386
 2 .model flat
 3 .stack 4096
 4 include io.h
 5 ExitProcess proto near32 stdcall, ExitCode:dword
 6 cr equ 0dh
 7 lf equ 0ah
 8 .data
 9 string1 byte "请输入汉诺塔数:", cr, lf
10 strNum byte 10 dup(?)
11 result byte 10 dup(' ')
12        byte cr, lf, 0
13 .code
14 ;递归时注意:在每一层的递归中,保证ebp基址指针的只是一样的(如果你使用了它)
15 Hanoi Proc near32
16   push ebp
17   mov ebp, esp
18   mov ecx, [ebp+20];得到当前剩余的砖块的数目
19   jecxz Finish
20 
21   ;完成n-1块从a柱子借助c柱子移向b柱子
22   dec ecx
23   push ecx
24   pushd [ebp+16]; a
25   pushd [ebp+8]; c
26   pushd [ebp+12]; b
27   call Hanoi
28   add esp, 16;移除参数 a, b, c, 和砖块数目
29 
30   ;完成a柱子上的最后一块移向c柱子
31    mov al, [ebp+16];得到a柱子的编号
32    mov result, al
33    mov al, '-'
34    mov result+1, al
35    mov al, '>'
36    mov result+2, al
37    mov al, [ebp+8];得到c柱子的编号
38    mov result+3, al
39    output result;输出移动结果
40  
41    ;完成n-1块从b柱子借助a柱子移向c柱子
42    mov ecx, [ebp+20]
43    dec ecx
44    push ecx; 得到剩下的盘子
45    push [ebp+12]; b
46    push [ebp+8]; c
47    push [ebp+16]; a
48    call Hanoi
49    add esp, 16;移除参数
50 Finish:
51     pop ebp;还原ebp指针
52     ret ;
53 Hanoi Endp
54 
55 _start:
56 output string1
57 input strNum, 10
58 atod strNum
59 push eax;初始化操作
60 pushd 'a'
61 pushd 'b'
62 pushd 'c'
63 call Hanoi
64 invoke ExitProcess, 0
65 public _start
66 end