Java基于栈方式解决汉诺塔问题实例【递归与非递归算法】

2025-05-29 0 23

本文实例讲述了Java基于方式解决汉诺塔问题。分享给大家供大家参考,具体如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118
/**

* 栈方式非递归汉诺塔

* @author zy

*

*/

public class StackHanoi

{

/**

* @param args

*/

public static void main(String[] args)

{

System.out.println("快网idc测试结果:");

System.out.println("递归方式:");

hanoiNormal(3, 'A', 'B', 'C');

System.out.println();

System.out.println("非递归方式:");

hanoi(3, 'A', 'B', 'C');

}

/**

* 递归汉诺塔

* @param n

* @param A

* @param B

* @param C

*/

public static void hanoiNormal(int n, char A, char B, char C)

{

//hanoiNormal(1, A, B, C)等价于直接移动A到C( move(A,C) )

if(n==1)

{

move(A, C);

return;

}

else

{

hanoiNormal(n-1, A, C, B);

move(A, C);

hanoiNormal(n-1, B, A, C);

}

}

/**

* 非递归汉诺塔

* @param n

* @param A

* @param B

* @param C

*/

public static void hanoi(int n, char A, char B, char C)

{

//创建一个栈

StateStack s = new StateStack();

//将开始状态进栈

s.push( new State(n, A, B, C) );

//保存出栈元素

State state = null;

//出栈

while((state = s.pop()) != null)

{

//如果n为1( hanoi(1,A,B,C) ),直接移动A->C

if(state.n == 1)

{

move(state.A, state.C);

}

//如果n大于1,则按照递归的思路,先处理hanoi(n-1,A,C,B),再移动A->C(等价于hanoi(1,A,B,C) ),然后处理hanoi(n-1,B,A,C),因为是栈,所以要逆序添加

else

{

//栈结构先进后出,所以需要逆序进栈

s.push( new State(state.n-1, state.B, state.A, state.C) );

s.push( new State(1, state.A, state.B, state.C) );

s.push( new State(state.n-1, state.A, state.C, state.B) );

}

}

}

/**

* 从s到d移动盘子

*/

public static void move(char s, char d)

{

System.out.println(s+"->"+d);

}

}

//状态

class State

{

public int n;

public char A;

public char B;

public char C;

public State(int n, char A, char B, char C)

{

this.n = n;

this.A = A;

this.B = B;

this.C = C;

}

}

//栈

class StateStack

{

private State[] storage = new State[1000];

//栈顶

private int top = 0;

//入栈

public void push(State s)

{

storage[top++] = s;

}

//出栈

public State pop()

{

if(top>0)

{

return storage[--top];

}

return null;

}

}

运行结果:

Java基于栈方式解决汉诺塔问题实例【递归与非递归算法】

希望本文所述对大家java程序设计有所帮助。

原文链接:http://zy3381.iteye.com/blog/1993895

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java基于栈方式解决汉诺塔问题实例【递归与非递归算法】 https://www.kuaiidc.com/113476.html

相关文章

发表评论
暂无评论