尝试这个:
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;
要找出开始的位置:
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;
}
}
您可以为终点做类似的事情。
如果您想将起点放在一个随机的空白点,您可以使用srand
and rand
。
首先,在程序开始时播种伪随机数生成器:
srand(time(0));
然后,确定一个随机起点:
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;
}
}
您可以以类似的方式将结束点放在随机的空白点中。
人们会这么说srand
,并且rand
不太擅长生成随机数。这是真的,但它应该足以满足您的需求。