gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:11:43 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com