java - 如何创建邻居的ArrayList来协调无向图中的节点?

标签 java matrix arraylist graph

给定一个二维数组矩阵,目标是找到所有相邻的坐标,将它们实例化为对象并将它们添加到 ArrayList 中以供以后使用。我遇到的问题是考虑邻居可能超出矩阵边界的边缘情况。那么,在 Java 中声明二维数组的边界以便它可以被条件语句捕获的最佳方法是什么?

尝试了以下操作。不确定如何解释其中一个邻居超出矩阵边界的情况(例如只有两个邻居的角节点)。


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

}

以下面的矩阵为例:

0, 0, 0
7, 1, 0
0, 7, 0 

最终的 ArrayList 应输出以下内容:

当前节点 = (1, 0),其中值等于 7。

邻居的ArrayList等于= {(0,0), (1,1), (2,0)} ,其中值分别等于 0、1、0。

最佳答案

我怀疑您想要做的是与您传递的数组的大小进行比较:

if (nodeX > 0)
    adjacentNodes.add(new Node(nodeX - 1, nodeY));
if (nodeX < enterGraph.length - 1)
    adjacentNodes.add(new Node(nodeX + 1, nodeY));
if (nodeY > 0)
    adjacentNodes.add(new Node(nodeX, nodeY - 1));
if (nodeY < enterGraph[nodeX].length - 1)
    adjacentNodes.add(new Node(nodeX, nodeY + 1));

关于java - 如何创建邻居的ArrayList来协调无向图中的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57967005/

相关文章:

c++ - 更快的四元数 vector 乘法不起作用

java - 创建<type>的新Arraylist与空类型<>的新Arraylist

android - 如何从 Arraylist 值创建 Json?

java - 如何使用 Apache httpComponent5 设置 Spring HttpComponentsClientHttpRequestFactory?

java - AspectJ 与 Web 服务和 Java 6。怎么办?

快速生产者的 Java "Tiered Queue"实现,慢速消费者

MATLAB:两个矩阵在一个索引上的逐元素乘法?

r - 以最小距离连接矩阵的两个坐标

javascript - 如何处理循环内的异步调用?

java - 连续单击 JButton 两次