java - 查找数组中元素周围的元素

标签 java arrays multidimensional-array

我有一个多维数组,我想获取该数组中特定元素周围的元素。

例如,如果我有以下内容:

[[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/

相关文章:

python - 使用numpy在python中矢量化空间距离

Java:如何在字符串中只允许使用整数和逗号?

无法创建整数数组来保存字符

c++ - 撤消或取消随机播放 C++ 随机播放函数

c - 文件需要正确读入

c++ - 我已经使用指针在 C++ 中声明了二维数组。如何将值初始化为数组

java - 使用 Tapestry 5 加载 jQuery

java - 从数组列表中删除元素不起作用,发生重复?(基本宾果游戏)

java - 有没有办法在一行中将分组列表连接到 Java 8 中的集合中?

Java:数组索引越界异常