2

我有一张由用户给出的尺寸为 N 和 M 的表格。该表仅填充 0 和 1。所以我得到这样的东西:

0 0 0 1 0
1 1 0 0 0
0 0 0 0 1
0 0 0 0 0
0 1 1 0 0

我的问题是,我如何计算围绕单个 1 的数量?

我是这样开始的:

int nb_neighbours_M(int **tab, int i, int j, int n, int m)
{

  int nb_neighbours = 0;`

  for (i = 0; i < n; i++)
  {
    for (j = 0; j < m; j++)
    {

    }
  }
}
4

2 回答 2

2

最简单的方法是有两个数组int drow[NUMBER_OF_DIRECTIONS]int dcol[NUMBER_OF_DIRECTIONS],它们存储每个单元格邻居的坐标变化。

// North, East, South, West
int drow[NUMBER_OF_DIRECTIONS] = {-1,  0, 1, 0};
int dcol[NUMBER_OF_DIRECTIONS] = {0, 1, 0, -1};

int row, col; // the coordinates of the cell you want to check the neighbours of
int num_neighbours = 0;

for (int i = 0; i < NUMBER_OF_DIRECTIONS; i++) {
        if (tab[row + drow[i]][col + dcol[i]] == 1) {
            num_neighbours++;
        }
}

在上面的示例中,我只处理 4 个方向,但您可以轻松地调整此代码段以处理 8 个方向,而无需修改任何实际代码(这是一件好事™)。

您可能还应该为此添加边界检查,因为它不执行任何操作。

于 2013-01-26T11:47:21.330 回答
2

通过展开循环,您可以获得类似的东西。

int count_neighbours (int **a, int x, int y, int w, int h)
{
  int res = 0;

  int left   = x <= 0;
  int right  = x >= w - 1;
  int top    = y <= 0;
  int bottom = y >= h - 1; 

  if (!left && !top)     res += a[x-1][y-1];
  if (!right && !bottom) res += a[x+1][y+1];
  if (!left && !bottom)  res += a[x-1][y+1];
  if (!right && !top)    res += a[x+1][y-1];
  if (!left)             res += a[x-1][y];
  if (!right)            res += a[x+1][y];
  if (!top)              res += a[x][y-1];
  if (!bottom)           res += a[x][y+1];

  return res;
}
于 2013-01-26T11:47:48.980 回答