Why does my maze solver not work?

╄→尐↘猪︶ㄣ 提交于 2019-12-02 16:06:12

问题


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?
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27115529/why-does-my-maze-solver-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!