gpt4 book ai didi

java - Knight's Tour 代码陷入无限循环,没有达成解决方案

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:38:57 25 4
gpt4 key购买 nike

我对 Knight's Tour 的递归回溯方法遇到了无限循环。起初,我认为这个问题通常可能会花费这么多时间,但有些解决方案可以立即解决。请告诉我的代码有什么问题。

package io.github.thegeekybaniya.InterviewPrep.TopTopics.Backtracking;

import java.util.Arrays;

public class KnightsTour {
private static int counter=0;

public static void main(String[] args) {

knightsTour(8);
}

private static void knightsTour(int i) {
int[][] board = new int[i][i];
for (int[] arr :
board) {
Arrays.fill(arr, -1);

}
board[0][0] = 0;
knightsTour(board,0,1);

}

private static boolean knightsTour(int[][] board, int cellno, int stepno) {
if (stepno == board.length * board.length) {
printBoard(board);
return true;
}

int[][] dirs = {
{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}
};
int row = cellno / board.length, col = cellno % board.length;
for (int i = 0; i < dirs.length; i++) {
int r = dirs[i][0] + row;
int c = dirs[i][1] + col;
if (isSafe(board, r, c)&&board[r][c]==-1) {
int ncell = r * board.length + c;
board[r][c] = stepno;
if (knightsTour(board, ncell, stepno + 1)) {
return true;
} else {
board[r][c] = -1;
}
}
}


return false;
}

private static boolean isSafe(int[][] board, int r, int c) {

return r >= 0 && c >= 0 && r < board.length && c < board.length;
}

private static void printBoard(int[][] board) {
System.out.println(++counter);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(board[i][j]+" ");

}
System.out.println();
}
}

}

最佳答案

您的代码中没有错误,只是由于搜索空间巨大,蛮力方法速度较慢。您可以通过实现 Warnsdorf's Rule 来加快搜索速度.这是选择下一步的启发式方法,在这种情况下,您总是会尝试为之后的下一步移动带来最少可用移动的移动。它可以通过几个简单的循环来完成:

int row = cellno / board.length, col = cellno % board.length;

// find move with fewest moves available for the next move:
int minMovesAvailable = 8;
int minMovesDir = 0;
for (int i = 0; i < dirs.length; i++) {
int r = dirs[i][0] + row;
int c = dirs[i][1] + col;
if (isSafe(board, r, c)&&board[r][c]==-1)
{
board[r][c] = stepno;
int movesAvailable = 0;
for (int j = 0; j < dirs.length; j++) {
int r2 = dirs[j][0] + r;
int c2 = dirs[j][1] + c;
if (isSafe(board, r2, c2)&&board[r2][c2]==-1)
{
movesAvailable++;
}
}
board[r][c] = -1;
if(movesAvailable < minMovesAvailable)
{
minMovesAvailable = movesAvailable;
minMovesDir = i;
}
}
}

// now recurse this move first:
// int r = dirs[minMovesDir][0] + row;
// int c = dirs[minMovesDir][1] + col;

关于java - Knight's Tour 代码陷入无限循环,没有达成解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53919872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com