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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <iostream>
#include <vector>
using namespace std;
class Row
{
public:
Row(const int size) : data(string(' ', size)), checked(false)
{
}
string data;
bool checked;
};
int get_empty_cell_count(vector<Row>& v, int r, int c)
{
int count(0);
if (r < 0 || c < 0 || v[r].checked)
return count;
if (v[r].data[c] == '.')
{
v[r].checked = true;
++count;
if (r != 0) // check previous row
count += get_empty_cell_count(v, r-1, c);
if (r != v.size()) // check next row
count += get_empty_cell_count(v, r+1, c);
// check rest of this row
// check to left:
int col = c;
while (c && v[r].data[--col] == '.')
++count;
// reset to c and check to the right:
col = c;
while (c < v[r].data.length() && v[r].data[++col] == '.')
++count;
}
return count;
}
int main()
{
int maze_size;
vector<Row> maze;
// get size of maze:
do
{
cout << "Enter the size of the maze, in the range 3 : 10 ";
cin >> maze_size;
cin.ignore();
} while (maze_size < 3 || maze_size > 10);
// get maze:
cout << "Enter lines for maze ('.' - empty cell, '*' - wall)" << endl;
for (int n = 0; n < maze_size; ++n)
{
Row r(maze_size);
cout << "Line #" << n <<": ";
cin.getline(&r.data[0], '\n');
r.data = r.data.substr(0, maze_size);
maze.push_back(r);
}
// get row and column from user:
int row(0), col(0);
cout << "Enter row and column, in the range 1 : " << maze_size << endl;
do
{
int r, c;
cin >> r >> c;
if ((r > 0 && r < maze_size) && (c > 0 && c < maze_size))
{
row = r;
col = c;
}
else
{
cout << "Invalid, try again" << endl;
}
} while (row == 0 && col == 0);
// find number of empty cells adjacent to and including row, col:
cout << get_empty_cell_count(maze, row-1, col-1);
cout << endl << endl << "Press [Enter] exit";
cin.ignore();
cin.get();
return 0;
}
|