Java实现加权图?

问题描述 投票:0回答:1

我编写了我的代码,但不知道如何访问图形的权重,或者如何在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);
        }


    }

}

java graph dijkstra weighted
1个回答
3
投票

第一点:通常,Node是顶点,Edge是边缘。你采用的名字可能会引起很多混乱。

答:如果您将图表表示为邻接列表,则最好使用NodeEdge。如果是这样的话,Node有一个label和一个Edges列表。 Edge有一些参考(在我的例子中,对Node对象的引用)到目的地Nodeweight

代码示例:

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(); 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.