(生命游戏)如何循环遍历矩阵的外层而不检查它的外部,同时检查邻居?

时间:2018-01-09 13:54:20

标签: algorithm logic matrix

矩阵中的每个点代表一个生存或死亡的细胞。我必须计算每个细胞有多少个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;
          }
        }
      }
    }
  } 
}
}

0 个答案:

没有答案