[英]Java implementing weighted graph?
I had written my code, but don't know how to access weight of graph, or how to print its edges in main method, please have look at my code. 我已经编写了代码,但是不知道如何访问图形的权重或如何在main方法中打印其边缘,请查看我的代码。 Please help,actually i trying to implement Dijkstra , but I don't know it is the correct way of including weight in the graph or not.
请帮忙,实际上我正在尝试实现Dijkstra,但是我不知道这是在图中添加权重的正确方法。 Please help trying to solve it from past three days.
请帮忙解决过去三天来的问题。
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);
}
}
} }
First note: Usually , Node
is the vertex and Edge
is an edge. 首先注意: 通常 ,
Node
是顶点, Edge
是边。 The names you've adopted may cause a lot of confusion. 您采用的名称可能会引起很多混乱。
Answer: It is good practice to use Node
and Edge
, if you are representing your graph as an Adjacency List . 答:如果将图形表示为邻接列表 ,则最好使用
Node
和Edge
。 If it is the case, The Node
has a label
and a list of Edge
s. 如果是这样,则
Node
具有label
和Edge
的列表。 Edge
has some kind of reference (in my example, a reference to the Node object) to the destination Node
and a weight
. Edge
具有对目标Node
和weight
某种引用(在我的示例中,是对Node对象的引用)。
Code example: 代码示例:
Node.java Node.java
public class Node {
private String label;
private List<Edge> edges;
}
Edge.java Edge.java
public class Edge {
private Node destination;
private double weight;
}
Usage example 使用范例
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.