C++二维地图找到给定索引的所有相邻方块

C++ 2 Dimensional Map find all adjacent squares to given index

本文关键字:索引 方块 二维 地图 C++      更新时间:2023-10-16

我很难想到一种有效的方法来找到 2d 容器中给定值的所有相邻方块。假设我有一个容器,表示为:

. . . . .
. G . . .
. . . . .
. . . . .
. . . . G

现在在我的程序中生成容器后(如上所示),我需要将所有相邻的G方块设置为 X ,因此映射应如下所示:

X X X . .
X G X . .
X X X . .
. . . X X
. . . X G

我觉得有一种比我目前使用这个解决方案更简单的方法。这是我的思考过程:

for r to container.size()
    for c to container.size()
        if r == 0                            //if we're at the first row, don't check above
            if c == 0                        //if we're at the first column, don't check to the left
            else if c == container.size() -1 //if we're at the last column, don't check to the right
        else if r == container.size()        //if we're at the last row, don't check below
            if c == 0                        //if we're at the first column, don't check to the left
            else if c == container.size() -1 //if we're at the last column, don't check to the right
        else if c == 0                       //if we're at the first column, don't check to the left
        else if c == container.size() - 1    //if we're at the last column, don't check to the right
        else                                 //check everything

这似乎是非常重复的,但是,我必须检查很多条件,以避免意外检查超出我的地图范围。我将为上面写的每个单独的if/else很多if(map[r][c+1] == "G")语句。有没有其他方法可以检查正方形是否与我没有想到的G相邻?

简化此操作的一种方法是在数据结构中添加边框,因此例如

char map[N+2][N+2];

然后像这样遍历地图:

for (i = 1; i <= N; ++i)
{
    for (j = 1; j <= N; ++j)
    {
        if (map[i][j] == 'G')
        {
            for (di = -1; di <= 1; ++di)
            {
                for (dj = -1; dj <= 1; ++dj)
                {
                    if (di == 0 && dj == 0)      // skip central value
                        continue;
                    map[i + di][j + dj] = 'X';   // set neighbouring values to 'X'
                }
            }
        }
    }
}

避免检出边界的一种可能方法是在每个方向上将矩阵扩展 1:

所以你有类似的东西

0 0 0 0 0 0 0
0 . . . . . 0
0 . G . . . 0
0 . . . . . 0
0 . . . . . 0
0 . . . . G 0
0 0 0 0 0 0 0

然后,如果您真的要检查,您只需要检查您的特殊值或者不检查您的算法,如上所述:

// index 0 and N + 1 are the surrounding
for (int x = 1; x != N + 1; ++x) {
    for (int y = 1; y != N + 1; ++y) {
        if (map[x][y] != 'G') {
            continue;
        }
        const int x_offsets[] = {-1, 0, 1, -1, 1, -1, 0, 1};
        const int y_offsets[] = {-1, -1, -1, 0, 0, 1, 1, 1};
        for (int i = 0; i != 8; ++i) {
#if 0 // if you don't want to modify surrounding
            if (map[x + x_offsets[i]][y + y_offsets[i]] == BORDER_SPECIAL_VALUE) {
                continue;
            }
#endif
            map[x + x_offsets[i]][y + y_offsets[i]] = 'X';
        }
    }
}
#define CHECK(x,y) x < 0 || x >= xsize || y < 0 || y >= ysize ? false : map[x,y]
for r to container.size()
    for c to container.size() 
        if CHECK(r-1,c-1)
            ...
        if CHECK(r-1,c)
            ...
        ...