简体   繁体   中英

Ways optimize my recursive maze solver?

I have developed the following C program to find all possible paths out off a maze. 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. 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.

#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..)

Secondly can you please explain the values in the boxes? as in 0,1,2 and 3? Is 3 the end of the maze or?...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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