I'm a beginner and I'm trying to figure out a way to get the corresponding neighbors of an index in a 2D array.
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;
}
public static int[][] findNeighbors(int[][] graph, int x, int y){
for (int i = 0; i < graph.length; i++){
for (int j = 0; j < graph[i].length; j++){
}
}
}
public static void main(String[] args) {
System.out.println(findNeighbors(graph(), 2, 2));
}
}
I created a simple 2D array above, and lets say I want to find the neighbors to index (2,2), so in this case given '13', I want to return the values '8', '18', '14, and '12'. I tried to use a nested for loop to get the values +- 1 but I couldn't really figure it out.