繁体   English   中英

使用ArrayLists在Java中创建图

[英]creating graphs in Java with ArrayLists

我是Java的新手,我想通过创建图形进行练习。 我在创建图形时遇到了麻烦,因为我不确定如何正确执行操作。 我缺乏逻辑,Java新手使事情变得非常困难。 我想知道是否有人可以帮助我或指导我走正确的道路! 谢谢!

基本上,我试图创建类似这样的图形。 一个节点将为其邻居包含一个ArrayList

    A,B,C,D
A = 0,1,3,0
B = 1,0,0,2
C = 1,0,0,3   //shorter path to A (cycle)
D = 0,0,3,0

节点相互连接,有或没有权重(如果我将数字更改为1)

这是我到目前为止(不完整)的内容:

public class GraphNode {
    boolean visited;


    public GraphNode() {
        List<GraphNode> node = new ArrayList<GraphNode>();  // store neighbors
        this.visited = false;

    }

    public void addNeighbor(GraphNode root, GraphNode target, int distance) {
        root.add(target);     // cannot use "add" to ArrayList

    }
}

为了能够从同一类中的各种方法访问ArrayList ,您需要将该局部变量提升为全局变量(字段),如下所示:

public class GraphNode {
    /*Global Variables*/
    boolean visited;
    List<GraphNode> nodeNeighbours;
    /*Global Variables*/

    public GraphNode() {
        this.nodeNeighbours = new ArrayList<GraphNode>();  // store neighbors
        this.visited = false;

    }

    public void addNeighbor(GraphNode target) {
        this.nodeNeighbours.add(target);    //This will add target to the neighbours of this given node.
    }
}

编辑:
最短路径算法(就内存而言)具有固定的起点,这意味着根将始终相同。 可以说它们的重量相同,通常不会改变。

但是,随着探索不同的路径,到根节点的距离最有可能改变。 考虑到这一点,您可以按照以下方式重新编写类:

public class GraphNode {
    /*Global Variables*/
    protected double weight;
    protected double distanceFromRoot;
    protected List<GraphNode> neighbours;
    protected boolean visited;
    /*Global Variables*/

    public GraphNode(double weight, double distanceFromRoot) {
        this.weight = weight;
        this.distanceFromRoot = distanceFromRoot;
        this.neighbours = new ArrayList<GraphNode>();
        this.visited = false;
    }

    public void setDistanceFromRoot(double distanceFromRoot) {
         this.distanceFromRoot = distanceFromRoot;
    }

    public void setVisited(boolean visited) {
         this.visited = visited;
    }

    public double getWeight() {
        return this.weight;
    }

    public double getDistanceFromRoot() {
        return this.distanceFromRoot;
    }

    public List<GraphNode> getNeighbours() {
        return this.neighbours;
    }   

    public void addNeighbour(GraphNode neighbour) {
        this.neighbours.add(neighbour)
    }
}

这可能比您开始时要广泛。 您的代码的主要变化是此代码促进了封装 封装是OOP的核心基础之一,在本质上您拒绝直接访问全局变量。 通过适当的setget方法提供访问,您可以使用该方法定义程序外部的人如何以及何时修改程序的内部状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM