(生命游戏)如何在不检查矩阵外部的情况下循环遍历矩阵的外层,同时检查邻居? [英] (Game of Life) How to loop through outer layer of a matrix without checking outside of it, simultaneously checking for neighbors?
问题描述
矩阵中的每个点代表一个活的或死的细胞.我必须计算每个单元格有多少个ALIVE邻居.我有一个可以完成此工作的函数,但是它会检查其边界之外的单元.我不知道如何在不执行大量if-else语句的情况下同时检查邻居并跟踪边缘.
Each point in the matrix represents a cell, living or dead. I have to count how many ALIVE neighbors each cell has. I have a function that does the job, but it checks for cells outside its boundary.I don't know how I can simultaneously check for neighbors and keep track of edges without doing a massive amount of if-else statements.
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;
}
}
}
}
}
}
}
推荐答案
处理此问题的最简单方法是添加两个虚拟行和列:矩阵上方的行,矩阵下方的行,矩阵左侧的列您的矩阵,以及矩阵右侧的一列.您可以将它们设置为DEAD一劳永逸,并且仅在原始矩阵中的单元格上运行循环.
The easiest way to handle this is to add two dummy rows and columns: a row above your matrix, a row below your matrix, a column to the left of your matrix, and a column to the right of your matrix. You set them to DEAD once and for all, and run your loops only on the cells in the original matrix.
这篇关于(生命游戏)如何在不检查矩阵外部的情况下循环遍历矩阵的外层,同时检查邻居?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!