简体   繁体   English

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

[英]Ways optimize my recursive maze solver?

I have developed the following C program to find all possible paths out off a maze. 我开发了以下C程序,以找到迷宫中所有可能的路径。 And it has to go through each room in the maze. 它必须穿过迷宫中的每个房间。 That is why the '54' is hard coded at the minute because for the 8*7 array I am passing in there are 54 open rooms. 这就是为什么'54'在这一刻要进行硬编码的原因,因为我经过的8 * 7阵列有54个开放房间。 I will work this out and pass it dynamically when I am re-writing. 我将解决这个问题并在重新编写时动态传递它。 However I am looking for some help in how to make the code more efficient - it finds over 300,000 possible paths to complete the maze I am passing in but it ran for almost an hour. 但是,我正在寻求有关如何使代码更高效的帮助-它找到了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;
}  

First of all I don't see any base condition for the function to return TRUE, it only returns TRUE on calling itself recursively witch is to say it will the result will allways print Failed (I thought recursion had to have a base condition that when finding success will propagate upwards..) 首先,我看不到该函数返回TRUE的任何基本条件,它仅在递归调用自身时返回TRUE,巫婆表示它将始终打印失败的结果(我认为递归必须具有一个基本条件,当找到成功将向上传播。)

Secondly can you please explain the values in the boxes? 其次,您能否解释一下方框中的值? as in 0,1,2 and 3? 如0,1,2和3? Is 3 the end of the maze or?... 3是迷宫的尽头还是?...

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

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