嗨,我试图在二维数组中获取所有相等的邻居或相邻值,我已经搜索了很多,但答案对我来说并不足够 示例:
`|1|0|1|`
`|0|1|1|`
`|0|1|0|`
相邻总数:4
int rowLimit = grid.length;
int columnLimit = grid.length;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
for(int x = Math.max(0, i-1); x <= Math.min(i+1, rowLimit); x++) {
for(int y = Math.max(0, j-1); y <= Math.min(j+1, columnLimit); y++) {
if(x != i || y != j) {
adj++;
}
}
}
}
}
System.out.println("Total adjacent:" + ady);
最佳答案
这是另一种算法(在我看来比你的更简单):
int[][] array = {{1, 0, 1}, {0, 1, 1}, {0, 1, 0}};
int counter = 0;
int rowLimit = array.length;
int colLimit = array[0].length;
for (int r = 0; r < rowLimit; r++)
{
for (int c = 0; c < colLimit; c++)
{
if ((c+1 < colLimit) && (array[r][c] == array[r][c+1]))
counter++;
if ((r+1 < rowLimit) && (array[r][c] == array[r+1][c]))
counter++;
}
}
关于java - 二维数组的相邻值 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45924189/