gpt4 book ai didi

c - Ce 中的迷宫回溯

转载 作者:太空宇宙 更新时间:2023-11-04 03:25:51 24 4
gpt4 key购买 nike

我正在尝试用 C 语言回溯迷宫。

我需要找到从 0 | 开始的最短路线0n | n.

我无法获得正确的输出。我没有看到我的错误。

我认为这是因为类型 char : int,但我不确定。

输入:Labyrinth.def

7 6
0 1 0 0 0 1 1
0 0 0 1 0 1 1
0 1 0 1 0 1 1
0 0 0 0 0 0 1
1 1 1 0 1 0 0
1 1 1 0 1 1 0

C 代码

#include <stdio.h>

#define MAXROWS 100
#define MAXCOLS 100
#define WEG '0'
#define MAUER '1'
#define MARKIERT 'x'
#define NOTFOUND 0
#define FOUND !NOTFOUND

typedef char Labyrinth[MAXROWS][MAXCOLS];

void search(Labyrinth l, int *done, int x, int y, int zx, int zy) {
//printf("position => %d | %d\n", x, y);
if (x == zx && y == zy) {
*done == FOUND;
}
else { //Weg suchen
if (!*done && y + 1 <= zy && l[y + 1][x] == WEG) { // runter
search(l, done, x, y + 1, zx, zy);
//printf("runter\n");
}
if (!*done && x + 1 <= zx && l[y][x + 1] == WEG) { // rechts
search(l, done, x + 1, y, zx, zy);
//printf("rechts\n");
}
if (!*done && y - 1 <= zy && l[y - 1][x] == WEG) {// hoch
search(l, done, x, y - 1, zx, zy);
//printf("hoch\n");
}
if (!*done && x - 1 <= zx && l[y][x - 1] == WEG) {// links
search(l, done, x - 1, y, zx, zy);
//printf("links\n");
}
if (!*done) {
l[y][x] = WEG;
//printf("log\n");
}
}
}

void loadLabyrinth(Labyrinth l, int *currRows, int *currCols) {
FILE *fp = NULL;
int i = 0;
int tmp = 0;

int x = 0;
int y = 0;

bool s = false;

//werte aus datei lesen
fp = fopen("labyrinth.def", "r"); //datei öffnen

if (fp != NULL) {
//printf("Datei geoeffnet\n");
while (!feof(fp)) {
fscanf(fp, "%d", &tmp); //datei int für int einlesen

if (s == false) {
if (i == 0) {
*currRows = tmp;
}
else if (i == 1) {
*currCols = tmp;
s = true;
i = 0;
}
}
else if (s == true) {
l[x][y] = (char)tmp;
x++;
if (i % *currRows == 0) {
x = 0;
y += 1;
}
}

i++;

//printf("%d", tmp);
}
}
else {
printf("Datei nicht gefunden ... :(\n");
}

fclose(fp); // datei schließen
}

void displayLabyrinth(Labyrinth l, int rows, int cols) {
for (int i = 0; i < cols; i++) {
for (int k = 0; k < rows; k++) {
printf("%i ", l[k][i]);
if (k + 1 == rows) printf("\n");
}
}
}

int main()
{
Labyrinth laby;

int currRows = 0;
int currCols = 0;
int geschafft = NOTFOUND;

int array[MAXROWS][MAXCOLS];

loadLabyrinth(laby, &currRows, &currCols); // Labyrinth laden

printf("%d %d\n", currRows, currCols);

displayLabyrinth(laby, currRows, currCols); // Labyrinth ausgeben

printf("\nLabyrinth geladen ! \n");
printf("Loesung wird gesucht ... \n\n");

//do {
search(laby, &geschafft, 0, 0, currCols - 1, currRows - 1);
//}while (geschafft != FOUND);

displayLabyrinth(laby, currRows, currCols); // Labyrinth ausgeben

getchar();
}

输出控制台:

48 1 0 0 0 1 1
0 0 0 1 0 1 1
0 1 0 1 0 1 1
0 0 0 0 0 0 1
1 1 1 0 1 0 0
1 1 1 0 1 1 0

最佳答案

Labyrinth中的元素是char,不是int,所以需要替换

printf("%i ", l[k][i]);

printf("%c ", l[k][i]);

关于c - Ce 中的迷宫回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41117178/

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