【问题标题】:How do I check the neighbors of the cells around me in a 2D array (C++)?如何在 2D 数组 (C++) 中检查我周围的单元格的邻居?
【发布时间】:2019-04-23 17:53:56
【问题描述】:

所以我试图检查任何给定 2D 数组的当前单元格周围的单元格是否具有特定值(0 或 1),并且取决于我想要计算总量的值(当前周围的总 1 个值单元格)但是我不确定如何获取下面的位置是我写的一些伪代码,我认为会考虑单元格所在的每个一般位置但是我不完全确定它是正确的,如果它是正确的我'不知道如何抓住周围的细胞。没有必要写出整个代码,但基本上我正在寻找位置的条件,以便在将来检查这些大 if 语句(如数组)的嵌套 if 语句 if array([xPosition+1][yPosition+1] == 1)

这是伪代码

if (xPosition==0 && yPosition==0) {


    } else if (xPosition==rows && yPosition==columns) {

    } else if (xPosition==rows && yPosition==0) {

    } else if (xPosition==0 && yPosition==columns) {

    } else if (xPosition==0) {

    } else if (xPosition==rows) {

    } else if (yPosition==0) {

    } else if (yPosition==columns) {

    } else {

    }

【问题讨论】:

  • 你为什么要这么做?一般来说,您只需根据地图边界检查您的 currentCellIndex + 或 - 1 以防止访问地图之外的内容,并且当 currentCellIndex +/- 1 在您的地图内时计算该值。
  • 这是针对我应该运行模拟的分配,规则状态取决于当前单元格可以从填充到未填充的周围单元格,反之亦然。所以我需要知道周围的单元格是否被填充。
  • 这听起来像Conways Game of Life,这是学习的常见任务。一个简单的技巧是使数组更大(带边框)。因此,您无需在阅读中检查边界。您只需调整循环以进行评估/写入以跳过边界单元格。

标签: c++ multidimensional-array


【解决方案1】:

你可以使用嵌套循环

int sum{0};
for (int x{std::max(xPosition, 1) - 1}; x < std::min(xPosition + 2, columns); ++x) {
    for (int y{std::max(yPosition, 1) - 1}; y < std::min(xPosition + 2, rows); ++y) {
        if (x == xPosition && y == yPosition) continue;
        sum += array[x][y];
    }
}

【讨论】:

    【解决方案2】:

    代码是不言自明的,我已经添加了 cmets

    bool isSafe(int xPosition, int yPosition, 
            int rows, int columns) { // checking the boundry
                return (xPosition >= 0 && xPosition < rows &&
                    yPosition >= 0 && yPosition < columns);
            }
    
    
    void checkNeighbours(int xPosition, int yPosition, 
                            int rows, int columns) {
            // Considering only 4 directions up, down , right, left                    
            int count = 0;
            if(isSafe(xPosition - 1, yPosition)) { // one cell up
                if(array[xPosition - 1][yPosition] == 1) {
                    count ++;
                }
            }           
    
            if(isSafe (xPosition + 1, yPosition)) { // one cell down
                if(array[xPosition + 1][yPosition] == 1) {
                    count ++;
                }
            }
    
            if(isSafe(xPosition, yPosition - 1)) { // one cell left
                if(array[xPosition][yPosition - 1] == 1) {
                    count ++;
                }
            }
    
            if(isSafe(xPosition, yPosition + 1)) { // one cell right
                if(array[xPosition][yPosition + 1] == 1) {
                    count ++;
                }
            }
    
            // use count for whatever
        }        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 2022-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多