In another post I found this way to find the neighbors of the current pixel in a 2d array. The solution considered diagonal pixels to be neighbors. I need a solution that gives only directly N, S, E, W. How would I be able to implement that into this code? The post I mentioned is found here: Finding valid neighbors in 2D array Any input/help is appreciated.
for(int x=0; x<matrix.length; x++) {
for(int y=0; y<matrix[0].length; y++) { //Iterate through length of column (y)
if(matrix[x][y] != 0) {
ArrayList<Integer> neighbors = new ArrayList<Integer>(); //Connected elements with the current element's value
//Checks pixels N,S,E,W of the current pixel
for(int nx=-1; nx<=1; nx++) {
for(int ny=-1; ny<=1; ny++) {
if(x+nx<0 || y+ny<0 || x+nx>labels.length-1 || y+ny>labels[0].length-1) {
continue;
}
else {
if (x + nx == 0 && x + ny == 0) {
continue;
}
if (labels[x + nx][y + ny] != 0) {
neighbors.add(labels[x + nx][y + ny]);
}
}
}
}