C++二维地图找到给定索引的所有相邻方块
C++ 2 Dimensional Map find all adjacent squares to given index
我很难想到一种有效的方法来找到 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)
...
...
相关文章:
- 数组索引的值没有增加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 查找最接近的大于当前数字的数字的索引
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- 跟随整数索引列表的自定义类迭代器
- 如何在for循环中包含两个索引值的测试条件
- D3D11-将混合权重和索引传递到顶点着色器
- 将转换字符键入 int 以用作向量C++的索引
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 如何为圆环创建索引
- 在子集化后将包含索引号的列表列表映射到标准索引序列
- 查找字符在两个索引之间出现的次数
- Azure Kinect 使用正文索引映射裁剪正文
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 数组索引重载错误
- C++二维地图找到给定索引的所有相邻方块