java - 二维数组的相邻值 (java)

标签 java arrays

嗨,我试图在二维数组中获取所有相等的邻居或相邻值,我已经搜索了很多,但答案对我来说并不足够 示例:

`|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/

相关文章:

java - 使用哪个阵列?

java - 与implicitwait()同步不起作用,为什么?

Java ClassNotFoundException html 错误

java - 将数组列表格式化为特定格式

arrays - 多个数组提供 UICollectionView 数据源

PHP - 将数组作为可变长度参数列表传递

Java AWS MySQL 和 hibernate

java 替换数组的元素

java - 将 float 组发送到部署在 Google Cloud ML-Engine 上的 Tensorflow 模型

java - 从 Object 类的对象访问整数