有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用ArrayList在Java中创建图形

我是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

    }
}

共 (1) 个答案

  1. # 1 楼答案

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

    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的核心基础之一,在OOP中,您基本上拒绝直接访问全局变量。通过适当的setget方法提供访问权限,您可以使用该方法定义程序外部的人如何以及何时修改程序的内部状态