java 算法 迭代 汉诺塔
static int x = 0; public static void main(String[] args) { int n = 4; moveCount(n); System.out.println("共需要:" + x + "步!"); moveStep(n, 1, 3); } /** * 统计步数 * @param n */ public static void moveCount(int n){ if(n == 0){ return; } if(n == 1){ x ++; } if(n > 1) { moveCount(n - 1); moveCount(1); moveCount(n - 1); } } /** * 移动过程 * @param n 子塔层数 * @param from 需要移动的子塔的目前位置 * @param dest 需要移动的子塔的目标位置 */ public static void moveStep(int n, int from, int dest){ if(n == 0){ return; } if(n == 1){ System.out.println(from + " --> " + dest); } if(n > 1) { moveStep(n - 1, from, getTempPosition(from, dest)); moveStep(1, from, dest); moveStep(n - 1, getTempPosition(from, dest), dest); } } /** * 获取临时位置 * @param now * @param dest * @return */ private static int getTempPosition(int now, int dest){ return 6 - now - dest; }
输出:
15
1 --> 2
1 --> 3
2 --> 3
1 --> 2
3 --> 1
3 --> 2
1 --> 2
1 --> 3
2 --> 3
2 --> 1
3 --> 1
2 --> 3
1 --> 2
1 --> 3
2 --> 3

浙公网安备 33010602011771号