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

标签 java arrays ccl

在另一篇文章中,我发现这种方法可以在二维数组中查找当前像素的邻居。该解决方案将对角像素视为邻居。我需要一个仅直接给出 N、S、E、W 的解决方案。我如何才能将其实现到此代码中? 我提到的帖子可以在这里找到: Finding valid neighbors in 2D array 感谢任何意见/帮助。

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

                }
            }
        }

关于java - 在二维数组中查找邻居(不包括对角线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60023150/

相关文章:

lisp - 为什么CCL中的round不正确?

common-lisp - OpenMCL Common Lisp 出现 "No MAKE-LOAD-FORM"错误

sockets - 如何在Clozure Common Lisp中通过套接字进行通信?

java - 在二维数组中移动的最佳方式(棋盘游戏)

php - 合并两个数组的行(将一个数组中的行数据附加到另一个数组中的行)

java - 如何在Java中生成以随机多边形为中心的多边形?

java - 小程序数据库访问问题

javascript - 从 json 中检索唯一值

java - 无法使用 spring javamail 从服务器 heroku 发送电子邮件

java - 在LWJGL的OpenCL功能中,我从哪里得出 "cl_platform_id"?