Why does my maze solver not work?

156 Views Asked by At

I'm trying to write a program that solves a specific inputted maze recursively and outputs it's position in the maze after each move.

Whenever I try and run my code, it immediately crashes and I get a "maze.exe has stopped working" error.

Why isn't my code working?

    #include <iostream>
#include <stdio.h>
using namespace std;
const int MazeHeight = 12;
const int MazeWidth = 16;

char Maze[MazeHeight][MazeWidth + 1] =
{
    {'S','.','.','.','.','#','.','.','.','#','.','.','.','.','.','.'},
    {'#','#','#','#','.','#','.','#','.','#','.','#','#','#','#','.'},
    {'.','.','.','.','.','#','.','#','.','.','.','#','.','#','#','.'},
    {'.','#','#','#','#','#','.','#','.','.','.','#','.','#','#','.'},
    {'.','.','.','.','.','.','.','#','.','#','#','#','.','#','#','.'},
    {'#','#','#','#','#','#','#','#','.','#','.','.','.','.','.','.'},
    {'.','.','.','.','.','.','.','.','.','#','#','#','#','#','#','.'},
    {'.','#','#','#','#','#','#','#','.','.','.','#','.','.','.','.'},
    {'.','.','.','.','.','.','.','#','#','#','.','#','#','#','#','#'},
    {'#','#','#','#','#','#','#','#','.','.','.','.','.','.','.','.'},
    {'.','.','.','.','.','.','.','#','#','#','#','#','#','#','#','.'},
    {'G','#','#','#','#','#','.','.','.','.','.','.','.','.','.','.'},
};



const char Wall = '#';
const char Free = '.';
const char Start = 'S';
const char End = 'G';

int solve(int X = 0, int Y = 0)
{
    while(Maze[Y][X] != End){

    if (Maze[Y][X] == End)
    {
        cout << X << Y << endl;
    }   

    else if (X > 0 && Maze[Y][X - 1] == Free && solve(X - 1, Y))
    {
        cout << X << Y << endl;
    }
    else if (X < MazeWidth && Maze[Y][X + 1] == Free && solve(X + 1, Y))
    {
        cout << X << Y << endl;
    }
    else if (Y > 0 && Maze[Y - 1][X] == Free && solve(X, Y - 1))
    {
        cout << X << Y << endl;
    }
    else if(Y < MazeHeight && Maze[Y + 1][X] == Free && solve(X, Y + 1))
    {
        cout << X << Y << endl;
    }

    else Maze[Y][X] = Free;
    }

    return 0;
}

int main(int argc, char** argv){

    // how do i call from here?
}
2

There are 2 best solutions below

0
On

When main is first called the runtime environment passes it arguments, so your default arguments aren't used. Rename the function and call it from main.

0
On

There maybe a good reason behind this but I'm not sure why you ignore your const int of 16 as max Width and make it 17 instead. Might not solve the problem but that sure looks wrong to me.

Also like a commenter said why initialise X and Y inside main's brackets? Why not just do it inside main. Or as the other poster said, turn that main function into a separate function then call it in a fresh main.