繁体   English   中英

如何优化我的递归迷宫求解器?

[英]Ways optimize my recursive maze solver?

我开发了以下C程序,以找到迷宫中所有可能的路径。 它必须穿过迷宫中的每个房间。 这就是为什么'54'在这一刻要进行硬编码的原因,因为我经过的8 * 7阵列有54个开放房间。 我将解决这个问题并在重新编写时动态传递它。 但是,我正在寻求有关如何使代码更高效的帮助-它找到了300,000条可能的路径来完成我传递的迷宫,但运行了将近一个小时。

#include <stdio.h>

#define FALSE 0
#define TRUE 1
#define NROWS 8
#define MCOLS 7

// Symbols:
//  0 = open
// 1 = blocked
// 2 = start
// 3 = goal
// '+' = path

char maze[NROWS][MCOLS] = {

    "2000000",
    "0000000",
    "0000000",
    "0000000",
    "0000000",
    "0000000",
    "0000000",
    "3000011"

};

int find_path(int x, int y, int c, int *t);

int main(void)
{   

    int t = 0;

    if ( find_path(0, 0, 0, &t) == TRUE )
        printf("Success!\n");
    else
        printf("Failed\n");

    return 0;

}

int find_path(int x, int y, int c, int *t)
{
    if ( x < 0 || x > MCOLS - 1 || y < 0 || y > NROWS - 1 ) return FALSE;

    c++;
    char oldMaze = maze[y][x];

    if ( maze[y][x] == '3' && c == 54) 
    {
        *t = *t+1;
        printf("Possible Paths are %i\n", *t);
        return FALSE;
    }

    if ( maze[y][x] != '0' && maze[y][x] != '2' ) return FALSE;

    maze[y][x] = '+';

    if ( find_path(x, y - 1, c, t) == TRUE ) return TRUE;

    if ( find_path(x + 1, y, c, t) == TRUE ) return TRUE;

    if ( find_path(x - 1, y, c, t) == TRUE ) return TRUE;

    if ( find_path(x, y + 1, c, t) == TRUE ) return TRUE;

    maze[y][x] = oldMaze;   
    return FALSE;
}  

首先,我看不到该函数返回TRUE的任何基本条件,它仅在递归调用自身时返回TRUE,巫婆表示它将始终打印失败的结果(我认为递归必须具有一个基本条件,当找到成功将向上传播。)

其次,您能否解释一下方框中的值? 如0,1,2和3? 3是迷宫的尽头还是?...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM