【发布时间】:2018-06-18 11:19:09
【问题描述】:
矩阵中的每个点代表一个细胞,无论是活的还是死的。我必须计算每个细胞有多少活着的邻居。我有一个可以完成这项工作的函数,但它会检查其边界之外的单元格。我不知道如何在不执行大量 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;
}
}
}
}
}
}
}
【问题讨论】:
-
如何使用第一个和最后一个虚拟列和行,用一些非活动值初始化?如有必要,将非活动值添加到可能的值中,并进行特殊处理。
-
这实际上是一道算法题,而不是一道 C 编程题。您正在寻找的是进行这些检查的最有效的方法,算法方面。实现“人生游戏”是一个经典的问题,所以肯定已经有人对此进行了思考。我建议在cs.stackexchange.com 提出这个问题。那么当你有了理想的理论算法后,你可以尝试用 C 来实现,然后在遇到实现问题时在这里询问。
-
请将您的 C/C#/C++/Java 代码替换为等效的伪代码。
-
我认为这是一个关于编程的问题,而不是算法。算法步骤是“检查每个邻居”,您在问如何有效地实现这一点。
-
@Lundin 作为 CS SE 的普通用户,我想说这绝对是题外话。该算法是“检查相邻的方块”,这里的问题是关于如何在编程语言语句级别实现该算法(具体来说,没有大量的
ifs 和elses)。 CS SE 不做“我应该如何实现这个?”
标签: c matrix logic indexoutofboundsexception conways-game-of-life