繁体   English   中英

Java实现加权图?

[英]Java implementing weighted graph?

我已经编写了代码,但是不知道如何访问图形的权重或如何在main方法中打印其边缘,请查看我的代码。 请帮忙,实际上我正在尝试实现Dijkstra,但是我不知道这是在图中添加权重的正确方法。 请帮忙解决过去三天来的问题。

public class Gr {

public class Node{ 
    public int vertex;
    public  int weight ;

    public int getVertex() {return vertex;}
    public int getWeight() {return weight;}
    public Node(int v , int w){
        vertex=v;
        weight=w;
    }

}
private int numVertices=1 ;
private  int numEdges=0 ;
private Map<Integer,ArrayList<Node>> adjListsMap= new HashMap<>();


public int getNumVertices(){
    return  numVertices;
}

public int addVertex(){
    int v = getNumVertices();
    ArrayList<Node> neighbors = new ArrayList<>();
    adjListsMap.put(v,neighbors);
    numVertices++ ;
    return (numVertices-1);
}

//adding edge
public void addEdge(int u , int v,int w ){
    numEdges++ ;
    if(v<numVertices&&u<numVertices){
        (adjListsMap.get(u)).add( new Node(u,w));
        (adjListsMap.get(v)).add(new Node(u,w));

    }
    else {
        throw new IndexOutOfBoundsException();
    }
}

//getting neighbours

public List<Node> getNeighbors(int v ){
    return new ArrayList<>(adjListsMap.get(v));
}



public static void main(String[] args){
    Gr g = new Gr();


        for(int j=1;j<=3;j++)
            g.addVertex();
        for(int k =1;k<=2;k++)
        {   int u= in.nextInt();
            int v = in.nextInt();
            int w = in.nextInt();
            g.addEdge(u,v,w);
        }


    }

}

首先注意: 通常Node是顶点, Edge是边。 您采用的名称可能会引起很多混乱。

答:如果将图形表示为邻接列表 ,则最好使用NodeEdge 如果是这样,则Node具有labelEdge的列表。 Edge具有对目标Nodeweight某种引用(在我的示例中,是对Node对象的引用)。

代码示例:

Node.java

public class Node {
  private String label;
  private List<Edge> edges;
}

Edge.java

public class Edge {
  private Node destination;
  private double weight;
}

使用范例

public class Main {
    public static void main(String[] args) {
        // creating the graph A --1.0--> B
        Node n = new Node();
        n.setLabel("A");
        Node b = new Node();
        b.setLabel("B");
        Edge e = new Edge();
        e.setDestination(b);
        e.setWeight(1.0);
        n.addEdge(e);

        // returns the destination Node of the first Edge
        a.getEdges().get(0).getDestination(); 
        // returns the weight of the first Edge
        a.getEdges().get(0).getWeight(); 
    }
}

暂无
暂无

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

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