我必须修改以下方法:
private final static int NUM = 6;
public void fun(int[][] grid) {
for(int row = 0; row < NUM; row++) {
for(int col = 0; col < NUM; col++) {
if((grid[row][col] % 2) == 0) {
grid[row][col] = 0;
}
}
}
}
此方法检查它是否是偶数,如果是,则将其值替换为 0。很简单。
我现在需要修改它,以便它指示每个单元格同时用其值为 0 的对角邻居的数量替换其值。
我想了大约一个小时并尝试了许多不同的解决方案,其中大多数都导致了越界异常。我很困惑,不知道如何实现这一点。
如果代码正确,使用下面的网格数组的整数,它将重现 picture 底部显示的数字。 .
最佳答案
问题出在哪里,您只需要添加 if 语句即可,例如最多可以有 4 个可能的邻居,因此请检查有多少个等于 0
。但这还不够,您只需在每个 if 语句中再添加一个条件即可。条件是您要检查的邻居是否可能。
即:共有 4 个邻居。如果主单元格的坐标是 x, y 那么:
第一个对角邻居:x-1
、y-1
第二个对角邻居:x-1
、y+1
第三个对角邻居:x+1
、y+1
第四个对角邻居:x+1
、y-1
这些都是 4 个对角邻居的坐标,但您需要检查的最后一件事是它们是否超出键。例如,为了检查第一个对角邻居,我会这样做:
if((x-1)>0 && (y-1)>0){
//and then check here if that block is = `0`
}
对于其他的例如x+1
或y+1
,你需要检查它们是否小于NUM。就像我想检查第三个对角邻居一样:
if((x+1)<NUM && (y+1)<NUM){
//and then check here if that block is = `0`
}
更新: 如果该 block = 0,则在此处检查是什么意思?
如果您想检查对角相邻 block 是否等于0
,那么您需要在循环中执行此操作。方法如下:
public void fun(int[][] grid) {
for(int row = 0; row < NUM; row++) {
for(int col = 0; col < NUM; col++) {
if((grid[row][col] % 2) == 0) {
grid[row][col] = 0;
}
}
}
for(row = 0; row< NUM; row++){
for(int col = 0; col < NUM; col++) {
int count = 0;
// To check for the 1st Diagonal Neighbor
if((row-1)>0 && (col-1)>0){
if(grid[row-1][col-1]==0){
count++;
}
}
//Similarly for 2nd, 3rd and 4th Diagonal Neighbors
//and then
grid[row][col]=count;
}
}
}
更新2:
比如说第三个对角邻居,代码块将如下所示:
if((row+1)<NUM && (col+1)<NUM){
if(grid[row+1][col+1]==0){
count++;
}
}
回答 最终私有(private)静态 int NUM = 6;
public void fun(int[][] grid) {
for(int row = 0; row < NUM; row++) {
for(int col = 0; col < NUM; col++) {
int counter = 0;
if((row - 1) > 0 && (col - 1) > 0) {
if(grid[row - 1][col - 1] == 0) {
counter++;
}
}
if((row - 1) > 0 && (col + 1) < NUM) {
if(grid[row - 1][col + 1] == 0) {
counter++;
}
}
if((row + 1) < NUM && (col - 1) > 0) {
if(grid[row + 1][col - 1] == 0) {
counter++;
}
}
if((row + 1) < NUM && (col + 1) < NUM) {
if(grid[row + 1][col + 1] == 0) {
counter++;
}
}
grid[row][col] = counter;
}
}
}
关于Java 2D 数组操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23052477/