vineetrok - 7 months ago 20

Java Question

I have a multidimensional array, I want to get the elements surrounding a particular element in that array. For example if I have the following:

`[[1,2,3,4,5,6]`

[8,9,7,5,2,6]

[1,6,8,7,5,8]

[2,7,9,5,4,3]

[9,6,7,5,2,1]

[4,7,5,2,1,3]]

How do I find all the 8 elements around any of the above elements. and how do I take care of elements at the edges.

One way I figured out is, to write a 9 line code for this , which is obvious, is there a better solution?

thanks

Answer

```
for (i = 0; i < array.length; i++) {
for (j = 0; j < array[i].length; j++) {
for (x = Math.max(0, i - 1); x <= Math.min(i + 1, array.length); x++) {
for (y = Math.max(0, j - 1); y <= Math.min(j + 1,
array[i].length); y++) {
if (x >= 0 && y >= 0 && x < array.length
&& y < array[i].length) {
if(x!=i || y!=j){
System.out.print(array[x][y] + " ");
}
}
}
}
System.out.println("\n");
}
}
```

Thanks to all the people who have answered, but i figured it out with the help of this post which i found just now, and above is the solution. thanks again :)