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]);
}
}
}
}
I think the following code will be enough for your use case.
int n = matrix.length;
int m = matrix[0].length;
ArrayList[][] neighbors = new ArrayList[n][m];
for(int x=0; x<matrix.length; x++) {
for(int y=0; y<matrix[0].length; y++) { //Iterate through length of column (y)
neighbors[x][y]= new ArrayList<Integer>();
if(matrix[x][y] != 0) {
//Checks pixels N,S,E,W of the current pixel
if (x-1 > 0 && labels[x-1][y]!=0)
{
neighbors[x][y].add(labels[x-1][y]);
}
if (x+1 < labels.length && labels[x+1][y]!=0)
{
//add neighbours
neighbors[x][y].add(labels[x-1][y]);
}
if (y-1 > 0 && labels[x][y-1]!=0 )
{
//
neighbors[x][y].add(labels[x-1][y]);
}
if (y+1 < labels[0].length && labels[x][y+1]!=0){
neighbors[x][y].add(labels[x-1][y]);
}
}
}
}