我创建了一个 12x12 的网格,在这个网格中我创建了“受感染”的方 block ,当一个受感染的方 block 被其他受感染的方 block 包围时,被包围的单元格变成患病的方 block 。我想知道是否有一种很好的方法来检查相邻的边界单元格的值?
public static void diseaseTiles() {
int i, j;
for(i = 0; i < 12; i++) {
for(j = 0; j < 12; j++) {
if(myGrid[i][j] == 'I'){
int left, right, up, down;
if(i == 0) {
left = 1;
}
if(i == 11) {
right = 1;
}
if(j == 0) {
up = 1;
}
if(j == 11) {
down = 1;
}
//this is where I've gotten stuck
//I was going to use the above int's to determine
//whether or not the adjacent tile in that direction
//should be checked (they're the border of the grid)
}
}
}
}
最佳答案
您可以利用短路评估来检查细胞是否被感染:
boolean leftInfected = (i!=0) && myGrid[i-1][j]=='I';
boolean rightInfected = (i!=11) && myGrid[i+1][j]=='I';
boolean topInfected = (j!=0) && myGrid[i][j-1]=='I';
boolean bottomInfected = (j!=11) && myGrid[i][j+1]=='I';
之后,您可以检查是否所有四个都被感染:
if (leftInfected && rightInfected && topInfected && bottomInfected) {
myGrid[i][j] = 'D';
}
关于java - 多维数组,如何检查与某些单元格相邻的所有相邻图 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20381284/