目前能够计算邻居总数,我只需要活着的邻居

Currently able to calculate total neighbors, I need just the neighbors that are alive

我有一个 bool [] 板,用于存储细胞是活的还是死的。我提供的代码正确地告诉了我每个单元格的邻居总数,问题是我只需要计算活着的邻居。我的想法是检查一下

   if (WithinBounds (row, col) ) {
      if (board[row, col] == true)
         liveNeighbor++;

这是我计算邻居总数的两种相关方法。

        private int TotalLiveNeighbors(int x, int y)
        {
            int liveNeighbors = 0;


            for (int row = x - 1; row <= x + 1; row++)
            {
                for (int col = y - 1; col <= y + 1; col++)
                {
                    if (! (row == x && col == y))
                    {
                        if (WithinBounds(row, col)) {
                            liveNeighbors++;
                        }

                    }
                }
            }

            return liveNeighbors;
        }

        public bool WithinBounds(int x, int y)
        {
            if (x < 0 || y < 0)
                return false;
            if (x >= 3 || y >= 3)
                return false;
            
            return true;
        }

我也在研究一种使用偏移量的不同方法:

int[,] neighborLocations = { { -1,-1 }, { -1,0 }, { -1, +1 },
                             { 0, -1},            { 0, +1 },
                             {+1, -1},  {+1, 0 }, { +1, +1 } };

int countAliveNeighbors (int x, int y) {
    int count = 0;
    foreach (int[] offset in neighborLocations) {
        if (board.hasAliveNeighborsAt(x + offset[1], y + offset[0])
            count++;
    }
    return count;
}

不确定这是否比我的第一种方法更有效

假设调用数组'alive'

 if (alive[row,col] && WithinBounds(row, col))