同样的程序在Java中以秒为单位执行,但在Python中却永远不会结束[关闭]。

问题描述 投票:0回答:1

我正在努力 骑士之旅 使用Backtracking算法解决的问题。我用Java和Python写了同样的程序,两者的行数几乎相同。有趣的是,Java程序在几秒钟内就能执行,而Python程序却花了很多时间(老实说,我从来没有看到它被执行过)。我检查了这两段代码近8个小时,但至今找不到我的失误,谁能指出我的错误。

下面是Java程序。

class KnightTour {
    static int N = 8;
    static int[][] Moves = { { +2, +1 }, { +1, +2 }, { -1, +2 }, { -2, +1 }, { -2, -1 }, { -1, -2 }, { +1, -2 },
            { +2, -1 } };

static boolean KT( int Board[][], int x, int y, int movei) {

    if (movei == N * N)
        return true;

    for (int[] move : Moves) {
        int r = x + move[0], c = y + move[1];
        if (0 <= r && r < N && 0 <= c && c < N && Board[r][c] == -1) {
            Board[r][c] = movei;

            if (KT(Board, r, c, movei + 1))
                return true;

            Board[r][c] = -1;
        }
    }

    return false;
}

public static void main(String args[]) {
    int Board[][] = new int[N][N];
    for (int x = 0; x < N; x++)
        for (int y = 0; y < N; y++)
            Board[x][y] = -1;

    Board[0][0] = 0;

    if (KT(Board, 0, 0, 1))
        for (int x = 0; x < N; x++) {
            for (int y = 0; y < N; y++)
                System.out.print(Board[x][y] + " ");
            System.out.println();
        }
}
}

这是输出结果

0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12

Python脚本。

def A(Board, at, visited):
    if visited == N * N:
        return True

    for r, c in [(+2, +1),(+1, +2),(-1, +2),(-2, +1),(-2, -1),(-1, -2),(+1, -2),(+2, -1)]:
        r = at[0] + r
        c = at[1] + c
        if 0 <= r < N and 0 <= c < N and Board[r][c] == -1:
            Board[r][c] = visited
            if A(Board, (r, c), visited + 1):
                return True
            Board[r][c] = -1

    return False


N = 8
Board = [[-1] * N for _ in range(N)]
Board[0][0] = 0
if A(Board, (0, 0), 1):
    print(*Board, sep="\n")

注:对于N<8,Python代码可以使用

java python algorithm backtracking
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.