在二维数组中查找邻居(不包括对角线)

Finding Neighbors in 2d Array (Not Including diagonal)

在另一个 post 中,我发现这种方法可以找到二维数组中当前像素的邻居。该解决方案将对角线像素视为邻居。我需要一个只直接给出 N、S、E、W 的解决方案。我如何才能将其实现到这段代码中? 我提到的 post 可以在这里找到: Finding valid neighbors in 2D array 任何 input/help 表示赞赏。

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]);
                                }
                            }
                        }
                    }

我认为以下代码足以满足您的用例。

        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]);
                    }

                }
            }
        }