[英]Adjacent values for a 2d array (java)
您好,我試圖在2d數組中獲取所有相等的鄰居或相鄰值,但我進行了大量搜索,但答案對我來說並不足夠:
`|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 rowLimit = array.length;
int columnLimit = array[0].length;
int actualValue;
int sum = 0;
for(int i = 0; i < rowLimit; i++) {
for(int j = 0; j < columnLimit; j++) {
actualValue = array[i][j];
for(int x = Math.max(0, i-1); x <= Math.min(i+1, rowLimit-1); x++){
for(int y = Math.max(0, j-1); y <= Math.min(j+1, columnLimit-1); y++){
if(x != i || y != j){
if(actualValue == array[x][y] && (Math.abs(x-i) + abs(y-j) == 1))
sum++;
}
}
}
}
}
System.out.println("Total adjacent: " + sum/2);
這是另一種算法(我認為比您更簡單):
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++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.