Hi im trying to get all neighbors or adjacent values that are equal, in a 2d array I've searching a lot but the answers are not the adequate for me example:
`|1|0|1|`
`|0|1|1|`
`|0|1|0|`
total adjacent: 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);
Here is a working solution:
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);
This is another algorithm (in my opinion more simple than yours):
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++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.