如何获取Java二维数组中指定索引的相邻元素?
二维数组指定索引的相邻元素查找方案
你要找指定索引的相邻元素,不用遍历整个数组,直接针对目标坐标的上下左右四个方向做合法性检查就可以。下面是修改后的完整代码,能正确返回(2,2)对应的8、18、14、12:
import java.util.ArrayList; import java.util.List; public class Main { public static int[][] graph(){ int[][] myGraph = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; return myGraph; } // 改成返回int[],更适合存储相邻元素的集合 public static int[] findNeighbors(int[][] graph, int x, int y){ List<Integer> neighbors = new ArrayList<>(); // 定义四个相邻方向的偏移:上、下、左、右 int[][] directions = {{-1,0}, {1,0}, {0,-1}, {0,1}}; for(int[] dir : directions){ int newX = x + dir[0]; int newY = y + dir[1]; // 检查新坐标是否在数组的合法范围内,避免越界 if(newX >= 0 && newX < graph.length && newY >= 0 && newY < graph[newX].length){ neighbors.add(graph[newX][newY]); } } // 把List转换为int数组返回 int[] result = new int[neighbors.size()]; for(int i = 0; i < neighbors.size(); i++){ result[i] = neighbors.get(i); } return result; } public static void main(String[] args) { int[] neighbors = findNeighbors(graph(), 2, 2); // 遍历打印结果 System.out.print("相邻元素:"); for(int num : neighbors){ System.out.print(num + " "); } } }
关键说明:
- 避免无效遍历:不需要循环整个数组,直接通过坐标偏移定位相邻位置,效率更高
- 越界检查:必须确认新坐标在数组的行列范围内,不然会抛出
ArrayIndexOutOfBoundsException - 返回类型调整:原方法返回
int[][]不符合需求,改成int[]更适合存储单个元素的集合 - 输出处理:直接打印数组会显示内存地址,需要遍历输出每个元素
如果需要包含对角线的8个相邻元素,只需要给directions数组添加四个对角线偏移:
int[][] directions = {{-1,0}, {1,0}, {0,-1}, {0,1}, {-1,-1}, {-1,1}, {1,-1}, {1,1}};
内容的提问来源于stack exchange,提问作者Natchy
相关产品推荐
相关产品推荐

