0

对于我的一项任务,我必须使用 getline 输入一个二维数组。迷宫设计是现场制作的。

16 10
################
#      #    #  #
# # #### ##   ##
# #      #######
# ###### #E    #
#S# #  # ### ### 
# # ## #     # #
# # ## ####### #
#              #
################

这是用于测试我们的回溯算法的示例输入之一。

16 10 是我们迷宫的列和行。

我想知道我将如何正确解析 getline 以便我的 2D 数组将使用给定的迷宫填充。

在旁注中,我做了一个练习,我不需要 cin 而是已经有了我的数组,我想知道如何告诉它从 S 开始。

抱歉,如果对此有疑问,但我并没有真正看到它以这种格式进入二维数组的地方,而您不知道数组大小。

4

2 回答 2

1

getline一次只能读取一行,因此您可能想要做的是使用for循环依次读取每一行并将其存储为二维数组的一行。

于 2012-10-20T22:33:36.883 回答
0

尝试这个:

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;
    }
}

您可以为终点做类似的事情。

如果您想将起点放在一个随机的空白点,您可以使用srandand 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不太擅长生成随机数。这是真的,但它应该足以满足您的需求。

于 2012-10-20T22:41:37.037 回答