矩阵中的每个点代表一个生存或死亡的细胞。我必须计算每个细胞有多少个ALIVE邻居。我有一个功能,但它检查边界外的单元格。我不知道如何在不执行大量if-else语句的情况下同时检查邻居并跟踪边缘。这是我的参考实现:
void Neighbours(int rows,
int cols, cell world[rows][cols],
int neighbors[rows][cols]) {
//Loop through each cell in the matrix.
for(int rCell = 0; rCell < rows; rCell++){
for(int cCell = 0; cCell < cols; cCell++) {
//Reset neighbor count for each cell.
neighbors[rCell][cCell] = 0;
//Check cell status in cell's vicinity of each cell.
for(int surroundR = -1; surroundR <= 1; surroundR++){
for(int surroundC = -1; surroundC <= 1; surroundC ++) {
//CONDITIONS
//1. If the cell is alive,
//2. if the cell is not itself,
//3. if it does exist within the boundaries of the matrix.
if(field[rCell - surroundR][cCell - surroundC].status == ALIVE) {
if(!(surroundR == 0 && surroundC == 0) && (rCell-surroundR < rows) && (cCell-surroundC < cols) && (cCell-surroundC >= 0) && (rCell-surroundR >= 0)) {
neighbors[rCell][cCell] += 1;
}
}
}
}
}
}
}