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 <iostream>
#include <vector>
#include <string>
enum { GOAL = '*', SPACE = ' ', WALL = '#', TRIED = '!', USED = '+' };
class maze {
std::vector<std::string> 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<<(std::ostream &os, maze const &m) {
for (auto const &s : m.data)
os << s << '\n';
return os;
}
size_t y_dim() { return data.size(); }
size_t x_dim() { return data[0].size(); }
};
bool solve(maze &m, size_t x = 0, size_t y=0) {
if (x < 0 || y < 0 || x >= 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).
y_dim()
andx_dim()
should beconst
. \$\endgroup\$enum: char { ... }
? Since you usestd::string
, I don't think that there is any advantage with letting it be implementation defined. \$\endgroup\$