在骑士巡回赛问题中需要回溯是至关重要的。您没有在代码中实现回溯的事实是它不起作用的主要原因。
要修复它,您至少必须在方法结束时清除位置。即,当你这样做时,ans[i][j] = count
你必须平衡它ans[i][j] = -1
以清除那个正方形 - 你没有这样做。
这不是您的代码的唯一问题,但它是主要问题。
存在回溯的替代方案。您可以在任何递归级别创建一个新板,它是当前板的副本,但通常被认为是浪费内存。
这是我最终得到的代码:
// The board size.
private static final int SIZE = 8;
// Contents of board squares when empty.
private static final int EMPTY = -1;
// The 8 possible x,y moves for the knight.
private static final int[] x = {2, 1, -2, 1, -1, -2, -1, 2};
private static final int[] y = {1, 2, 1, -2, -2, -1, 2, -1};
public static void printBoard(int[][] board) {
// Print out the board.
for (int d = 0; d < SIZE; d++) {
for (int e = 0; e < SIZE; e++) {
System.out.print(board[d][e] + " ");
}
System.out.println();
}
}
public static boolean knightsMove(int[][] board, int i, int j, int count) {
boolean finished = false;
// Only step onto empty squares that are on the board.
if (i >= 0 && i < SIZE && j >= 0 && j < SIZE && board[i][j] == EMPTY) {
// Mark my route.
board[i][j] = count;
// Count up.
count += 1;
// Are we done?
if (count > SIZE * SIZE) {
System.out.println("=== Solution ===");
// Print the solution.
printBoard(board);
// Finished now.
return true;
}
if (count == SIZE * SIZE) {
// Nearly there - print something to show progress.
System.out.println("=== Try === (" + i + "," + j + ")=" + count);
// Print the current state.
printBoard(board);
}
// Look around to try all moves from here.
for (int u = 0; u < x.length && !finished; u++) {
// Try the next place.
finished = knightsMove(board, i + x[u], j + y[u], count);
}
// Clear my trail - you missed this.
board[i][j] = EMPTY;
} else {
// Cannot go there.
return false;
}
return finished;
}
public static void knightsMove() {
int[][] board = new int[SIZE][SIZE];
// Clear to EMPTY.
for (int d = 0; d < board.length; d++) {
for (int e = 0; e < board[d].length; e++) {
board[d][e] = EMPTY;
}
}
// Start at (7,7) with count 1.
knightsMove(board, 7, 7, 1);
}
请耐心等待 - 这需要很长时间才能完成 - 正如您所期望的那样。在我的电脑上,大约需要 20 分钟才能到达:
=== Solution ===
29 42 51 60 27 22 17 24
50 59 28 41 52 25 20 15
43 30 61 26 21 16 23 18
62 49 58 53 40 19 14 7
57 44 31 48 33 8 3 10
36 63 34 39 54 11 6 13
45 56 37 32 47 2 9 4
64 35 46 55 38 5 12 1
我做了以下更改:
- 添加评论 - 您应该始终评论您的代码。
- 制作你的
x
和y
数组static
- 它们不需要是参数。
- 在一个地方完成所有支票(在船上和空的)。
- 在未遂事件上打印板,只是为了让您开心。
- 用 a
static final
EMPTY
表示空。
- 完成后返回
boolean
结果以停止搜索。
- 添加了回溯。
- 使用更好的名称,例如
board
和knightsMove
。
- 用于电路板尺寸的常数
SIZE
。
- 可能是一些小的调整。
请不要将此代码用于您的作业 - 通过自己执行此操作并了解每个部分的工作原理,您将学到更多。