Given a 2d array matrix, the goal is to locate all adjacent coordinates, instantiate them as objects and add them to an ArrayList for later use. The issue I'm having is accounting for edge cases where the neighbors might be out of matrix bounds. With that, what is the best method to state the bounds of a 2d array in Java so that it maybe caught by a conditional statement?
Tried the following below. Unsure how to account for cases where one of the neighbors is outside of the matrix bounds (ex. a corner node with only two neighbors).
import java.util.ArrayList;
class Node{
private int nodeX;
private int nodeY;
public Node(int enterX, int enterY){
nodeX = enterX;
nodeY = enterY;
}
public ArrayList<Node> getNeighbors(int[][] enterGraph){
ArrayList<Node> adjacentNodes = new ArrayList<>();
if(this.nodeX + 1 > /*Farthest value right in row*/){
Node right = new Node(this.nodeX + 1, this.nodeY);
adjacentNodes.add(right);
}
if(this.nodeX - 1 < /*Farthest value left in row*/){
Node left = new Node(this.nodeX - 1, this.nodeY);
adjacentNodes.add(left);
}
if(this.nodeY + 1 < /*Farthest value up in row*/){
Node up = new Node(this.nodeX, this.nodeY + 1);
adjacentNodes.add(up);
}
if(this.nodeY - 1 < /*Farthest value down in row*/){
Node down = new Node(this.nodeX, this.nodeY - 1);
adjacentNodes.add(down);
}
return adjacentNodes;
}
}
Take for instance the following matrix:
0, 0, 0
7, 1, 0
0, 7, 0
The final ArrayList should output the following:
Current node = (1, 0), where value equals 7.
ArrayList of neighbors equals = {(0,0), (1,1), (2,0)}
, where values equal 0, 1, 0 respectively.