Try this:
size_t num_rows;
size_t num_cols;
cin >> num_rows >> num_cols;
char* maze = new char[num_rows * num_cols];
for (size_t row = 0; row < num_rows; row++)
{
string line;
getline(cin, line);
if (line.size() != num_cols)
{
cerr << "Error! Size is " << line.size() << " rather than " << num_cols << endl;
exit(1);
}
for (size_t col = 0; col < num_cols; col++)
{
maze[(row * num_cols) + col] = line[col];
}
}
cout << "Maze is: " << endl;
for(int row = 0; row < num_rows; row++)
{
for(int col = 0; col < num_cols; col++)
{
cout << maze[(row * num_cols) + col];
}
cout << endl;
}
delete [] maze;
To figure out where start is:
size_t start_row, start_col;
for(int row = 0; row < num_rows; row++)
{
bool found = false;
for(int col = 0; col < num_cols; col++)
{
if (maze[(row * num_cols) + col] == 'S')
{
start_row = row;
start_col = col;
found = true;
break;
}
}
if (found)
{
break;
}
}
You can do similar things for the end point.
If you want to put the start point at a random empty spot, you can use srand
and rand
.
First, seed the pseudorandom number generator at the beginning of your program:
srand(time(0));
Then, determine a random start point:
size_t start_row, start_col;
bool found = false;
while (!found)
{
start_row = rand() % num_rows;
start_col = rand() % num_cols;
if (isspace(maze[(start_row * num_cols) + start_col]))
{
maze[(start_row * num_cols) + start_col] = 'S';
found = true;
}
}
You can put the end spot in a random empty spot in a similar way.
People will sy that srand
and rand
aren't very good at generating random numbers. That is true, but it should be sufficient for your needs.