gpt4 book ai didi

c++ - 骑士之旅回溯无限循环

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

我正在尝试为 the Knight's Tour 编写代码:

A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square exactly once.

我一直在尝试更改其他人的代码,但回溯似乎无法正常工作 - 它从未找到解决方案。当骑士从 0, 0 开始时,它工作得很好,但如果它从 2D 网格上的任何其他点开始,程序将永远运行下去。

这段代码的错误在哪里?

#include <iostream>
#include <ctime>
using namespace std;

const int N = 8;
int map[N][N];

/* A utility function to check if i,j are valid indexes for N*N chessboard */
bool isSafe(int x, int y) {
return x >= 0 && x < N && y >= 0 && y < N && map[x][y] == -1;
}

/* A utility function to print solution matrix sol[N][N] */
void printSolution() {
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++)
cout << map[x][y];
cout << endl;
}
}

/* A recursive utility function to solve Knight Tour problem */
bool knightsTourRecursive(int x, int y, int movei, int xMove[N], int yMove[N]) {
int nextX, nextY;

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

/* Try all next moves from the current coordinate x, y */
for (int k = 0; k < 8; k++) {
nextX = x + xMove[k];
nextY = y + yMove[k];

if (isSafe(nextX, nextY)) {
map[nextX][nextY] = movei;

if (knightsTourRecursive(nextX, nextY, movei+1, xMove, yMove)) // recursion
return true;
else
map[nextX][nextY] = -1; // backtracking
}
}
return false;
}

bool knightsTour() {
/* Initialization of solution matrix */
for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
map[x][y] = -1;

/* xMove[] and yMove[] define next move of Knight.
xMove[] is for next value of x coordinate
yMove[] is for next value of y coordinate */
int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };

int initX = rand() % N;
int initY = rand() % N;

cout << "Starting at " << initX << " " << initY << endl;

// Since the Knight is initially at the first block
map[initX][initY] = 0;

/* explore all tours using solveKTUtil() */
if(!knightsTourRecursive(initX, initY, 1, xMove, yMove) ) {
cout << "Solution does not exist" << endl;
return false;
}
else
printSolution();

return true;
}

int main() {
srand( (unsigned) time(0));
knightsTour();

cin.get();
return 0;
}

最佳答案

这个程序似乎是绝对正确的,我看不出这段代码有什么错误。

但是,骑士之旅是一个非常复杂的算法。实际上,该程序需要检查多达 64!=1*2*3*...*64 种不同的方式。这是一个有 89 个零的数字!

在许多情况下,回溯会在较早的分支处停止,但有些分支会永远向上。

如果从 0,0 开始的巡回路线被发现得如此之快,那么这可能纯粹是偶然,或者数组 xMove 和 yMove 被巧妙地初始化,以便快速找到 (0,0) 的解决方案。

所以问题不在于你的程序,而在于算法。我建议你对这个话题做一些研究。骑士之旅有很多算法,可以在更合理的时间内给你一个解决方案。

关于c++ - 骑士之旅回溯无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073258/

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