如何找到迭代解决方案

时间:2015-04-13 13:52:04

标签: java recursion iteration

任何人都可以给我一个河内塔的迭代解决方案 我理解这个递归代码

public class MainClass {
    public static void main(String[] args) {
        int nDisks = 3;
        doTowers(nDisks, 'A', 'B', 'C');
    }

    public static void doTowers(int topN, char from, char inter, char to) {
        if (topN == 1) {
            System.out.println("Disk 1 from " + from + " to " + to);
        } else {
            doTowers(topN - 1, from, to, inter);
            System.out.println("Disk " + topN + " from " + from + " to " + to);
            doTowers(topN - 1, inter, from, to);
        }
    }
}

但是我发现在实现不使用堆栈的迭代函数方面存在困难,而不是一点点算法。

1 个答案:

答案 0 :(得分:0)

public class hanoi {
    static public void main(String args[]) {
        int N = 4; // number of discs
        int nummoves, second = 0, third, pos2, pos3, j, i = 1;
        int[] locations = new int[N + 2];
        for (j = 0; j < N; j++) {
            locations[i] = 0;
        }
        locations[N + 1] = 2;
        nummoves = 1;
        for (i = 1; i <= N; i++) {
            nummoves *= 2;
        }
        nummoves -= 1;
        for (i = 1; i <= nummoves; i++) {
            if (i % 2 == 1) {
                second = locations[1];
                locations[1] = (locations[1] + 1) % 3;
                System.out.print("Move disc 1 to ");
                System.out.println((char) ('A' + locations[1]));
            } else {
                third = 3 - second - locations[1];
                pos2 = N + 1;
                for (j = N + 1; j >= 2; j--) {
                    if (locations[j] == second) {
                        pos2 = j;
                    }
                }
                pos3 = N + 1;
                for (j = N + 1; j >= 2; j--) {
                    if (locations[j] == third) {
                        pos3 = j;
                    }
                }
                System.out.print("Move disc ");

                if (pos2 < pos3) {
                    System.out.print(pos2);
                    System.out.print(" to ");
                    System.out.println((char) ('A' + third));
                    locations[pos2] = third;
                } else {
                    System.out.print(pos3);
                    System.out.print(" to ");
                    System.out.println((char) ('A' + second));
                    locations[pos3] = second;
                }
            }
        }
    }
}