1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <iostream>
int constexpr rows = 8, cols = 8;
char maze[rows * cols]
{
' ',' ',' ',' ',' ',' ','X',' ',
'X',' ',' ','X','X',' ','X',' ',
' ','X',' ',' ','X',' ',' ',' ',
' ',' ','X',' ',' ','X','X',' ',
' ','X','X','X',' ',' ',' ',' ',
' ',' ',' ','X',' ',' ','X',' ',
' ','X',' ','X',' ','X',' ',' ',
' ','X',' ',' ',' ',' ',' ','X',
};
[[nodiscard]] int constexpr xy(int x, int y) { return y * cols + x; }
[[nodiscard]] bool constexpr in_halfopen(int val, int lb, int ub)
{ return val >= lb && val < ub;}
[[nodiscard]] bool constexpr in_bounds(int x, int y)
{ return in_halfopen(x, 0, cols) && in_halfopen(y, 0, rows); }
[[nodiscard]] bool constexpr passable(int x, int y)
{ return in_bounds(x, y) && maze[xy(x, y)] == ' '; }
int constexpr exit_square = xy(0, 7);
bool find_exit(char* maze, int x, int y)
{
if (! passable(x, y)) return false; // can't move through walls
if (xy(x, y) == exit_square) return true; // "base case"; found the exit
maze[xy(x, y)] = '.'; // "choose"; leave a breadcrumb
// "explore"; search for the exit from adjacent squares
if (find_exit(maze, x - 1, y) || find_exit(maze, x + 1, y) ||
find_exit(maze, x, y - 1) || find_exit(maze, x, y + 1))
return true;
maze[xy(x, y)] = ' '; // "un-choose"; couldn't find the exit from here
return false;
}
int main()
{
find_exit(maze, 0, 0);
for (int y = 0; y < rows; ++y)
{
for (int x = 0; x < cols; ++x) std::cout << maze[xy(x, y)] << ' ';
std::cout << '\n';
}
}
|