試試這個:
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
和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;
}
}
你可以把結束點隨機空以類似的方式發現。
人們將sy srand
和rand
不擅長隨機數字的產生。這是真的,但它應該足以滿足您的需求。
像這樣:http://stackoverflow.com/questions/12992600/convert-string-to-char-2d-array?也許你們有相同的功課。 –
我回答了這個問題。有關直接鏈接,請參閱:http://stackoverflow.com/a/12992851/1732980。 –
不一樣,但我相信這會奏效。其基本相同,只是我必須設置我的列和行。 TY –