HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Recursive maze solver

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mazerecursivesolver

Problem

Up for review today is some C++11 code to recursively search a maze for a path to a specified goal. This one shows dead-ends it explored on the way to finding the solution.

#include 
#include 
#include 

enum { GOAL = '*', SPACE = ' ', WALL = '#', TRIED = '!', USED = '+' };

class maze {
    std::vector data;
public:
    char &operator()(size_t x, size_t y) {
        return data[y][x];
    }

    friend std::istream &operator>>(std::istream &is, maze &m) {
        std::string temp;
        while (std::getline(is, temp))
            m.data.push_back(temp);
        return is;
    }

    friend std::ostream &operator= m.x_dim() || y >= m.y_dim())
        return false;

    if (m(x, y) == GOAL) 
        return true;

    if (m(x, y) != SPACE)
        return false;

    m(x, y) = USED;

    bool solved 
         = solve(m, x - 1, y)
        || solve(m, x + 1, y)
        || solve(m, x, y - 1)
        || solve(m, x, y + 1);

    if (!solved)
        m(x, y) = TRIED;

    return solved;
}

int main(){
    maze m;
    std::cin >> m;

    solve(m);
    std::cout << m;     
}


Input is a simple text file of walls, spaces, and a goal, such as:

#######
#    # ##
# ####  #
#      ##
# ### ###
#####  *#


Searching always commences from position 0, 0 (i.e., the top, left corner).

Solution

Try and engage the move constructor:

m.data.push_back(temp);


Because temp is a named variable it will hit the version that uses const& T. To try and get the alternative version that engages the move constructor add std::move

m.data.push_back(std::move(temp));


The input operator does not make any attempt to make sure each line is the same size.

size_t x_dim() { return data[0].size(); }


So the above may not be accurate.

You can add a fake set of cells at the top/bottom/left/right of type 'WALL' then you don't need the test if (x = m.x_dim() || y >= m.y_dim()) as it can never reach outside the bounds of the maze (this can be forced to be true because it is part of the code and not part of the user input). This means you don't need y_dim() as that is the only use case.

My main issue is that solve() actually mutates the maze object. Some form of visitor pattern may be a more re-usable technique, or solve() would be better as a member of maze().

Code Snippets

m.data.push_back(temp);
m.data.push_back(std::move(temp));
size_t x_dim() { return data[0].size(); }

Context

StackExchange Code Review Q#48909, answer score: 11

Revisions (0)

No revisions yet.