我有一个多维数组,我想获取围绕该数组中特定元素的元素。
例如,如果我有以下内容:
[[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]]
如何找到上述任何一个元素附近的所有8个元素?以及如何处理边缘的元素?
我发现的一种方法是为此编写9行代码,这很明显,但是有更好的解决方案吗?
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");
}
}
感谢所有回答的人,但是我借助我刚刚发现的这篇帖子找到了答案,而以上就是解决方案。再次感谢 :)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句