【发布时间】:2021-07-31 12:35:49
【问题描述】:
#include <stdio.h>
#define SIDE 8
#define VISITED 1
#define NOT_VISITED 0
#define FALSE 0
#define TRUE !FALSE
void printBoard(int board[][SIDE]);
int goHorsie(int board[][SIDE], int x, int y, int step, int cor1, int cor2, int cor3);
int main(void)
{
int board[SIDE][SIDE] = { NOT_VISITED };
int found = 0;
found = goHorsie(board, 0, 0, 1, 0, 0, 0);
if (found)
{
printf("Yes, there is a path from 0,0 through all corners! Here it is:\n");
printBoard(board);
}
else
{
printf("No path from 0,0 through all corners\n");
printBoard(board);
}
getchar();
return 0;
}
int goHorsie(int board[][SIDE], int x, int y, int step, int cor1, int cor2, int cor3)
{
int res = FALSE, check = 1;
if (board[x][y] != NOT_VISITED //We were here already!
|| x >= SIDE || y >= SIDE || x < 0 || y < 0)
{
res = FALSE;
check = 0;
}
if (x == 7 && y == 7)
{
printf("1)found!\n");
cor1 = 1;
}
if (x == 7 && y == 0)
{
printf("2)found!\n");
cor2 = 1;
}
if (x == 0 && y == 7)
{
printf("3)found!\n");
cor3 = 1;
}
if (cor1 == 1 && cor2 == 1 && cor3 == 1)
{
printf("FOUND ALL!\n");
return TRUE;
}
else if(check == 1)
{
board[x][y] = step;
step++;
res =
goHorsie(board, x + 1, y - 2, step, cor1, cor2, cor3) ||
goHorsie(board, x + 2, y + 1, step, cor1, cor2, cor3) ||
goHorsie(board, x + 2, y - 1, step, cor1, cor2, cor3) ||
goHorsie(board, x + 1, y + 2, step, cor1, cor2, cor3) ||
goHorsie(board, x - 2, y + 1, step, cor1, cor2, cor3) ||
goHorsie(board, x - 2, y - 1, step, cor1, cor2, cor3) ||
goHorsie(board, x - 1, y + 2, step, cor1, cor2, cor3) ||
goHorsie(board, x + 1, y - 2, step, cor1, cor2, cor3);
if (!res)
{
board[x][y] = NOT_VISITED;
}
}
return res;
}
void printBoard(int board[][SIDE])
{
int i = 0, j = 0;
for (int i = 0; i < SIDE; i++)
{
for (int j = 0; j < SIDE; j++)
{
printf("%3d", board[i][j]);
}
printf("\n");
}
}
我正在使用递归来找到所有 3 个角的路径。
我现在运行程序大约 20 分钟,但仍然没有找到解决方案。
我知道为什么它花了太长时间,但不确定它是否能让我得到答案,我认为它会永远循环。
所以我的问题是我是否使函数正确,它最终会给我正确的答案(通往所有 3 个角落的路径),或者我需要更改什么才能获得答案。
我所说的三个角是:右上角、右下角和左下角。
【问题讨论】:
-
你需要展示你如何初始化
board以及你如何进行第一次函数调用 -
我不清楚您要查找的内容。是 a) 一个 路径让您访问所有三个角落还是 b) 三个路径,即每个角落一个路径?
-
投票只是因为你的代码的函数名字太棒了:
goHorsie -
我试图找到 1 条覆盖所有 3 个角的路径
-
如果您引入宏(常量会更好),请使用它们来避免幻数。例如。 7 ->
SIDE-1。如果您开始有一个变量res的概念,请保持一致并且没有两个返回。你的if-tree 应该有更多的else ifs。您存储在cor123中的信息仅用于更深层次的递归。如果您留下一次递归,则有关已找到角点的信息将丢失。使用指向int的指针。
标签: c recursion chess knights-tour