gpt4 book ai didi

C++ 2 Dimensional Map 找到给定索引的所有相邻方 block

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:44:59 25 4
gpt4 key购买 nike

我很难想出一种有效的方法来找到二维容器中给定值的所有相邻方 block 。假设我有一个容器表示为:

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

现在在我的程序中生成容器后(如上所示),我需要将 G 的所有相邻方 block 设置为 X,因此 map 应该看起来喜欢:

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

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

最佳答案

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

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

然后像这样遍历 map :

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

关于C++ 2 Dimensional Map 找到给定索引的所有相邻方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27494587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com