我有一个多维数组,我想获取该数组中特定元素周围的元素。
例如,如果我有以下内容:
[[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 行代码,这很明显,但是有没有更好的解决方案?
最佳答案
你可以在表单中使用'direction array'
[[-1,-1], [-1,0],[1,0]..and so on]
以及获取点坐标并遍历方向数组的方法 -> 将方向数字添加到坐标,检查索引是否越界并收集结果。 像这样:
private static int[][] directions = new int[][]{{-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0, -1}};
static List<Integer> getSurroundings(int[][] matrix, int x, int y){
List<Integer> res = new ArrayList<Integer>();
for (int[] direction : directions) {
int cx = x + direction[0];
int cy = y + direction[1];
if(cy >=0 && cy < matrix.length)
if(cx >= 0 && cx < matrix[cy].length)
res.add(matrix[cy][cx]);
}
return res;
}
关于java - 查找数组中元素周围的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12743748/