-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEdgeWeightDigraph.java
More file actions
54 lines (49 loc) · 1.45 KB
/
EdgeWeightDigraph.java
File metadata and controls
54 lines (49 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.Random;
public class EdgeWeightDigraph{
private int V;
private int E=0;
private Bag<DirectedEdge>[] adj;
public EdgeWeightDigraph(int v){
this.V=v;
adj=(Bag<DirectedEdge>[]) new Bag[v];
for (int i=0;i<v;i++){
adj[i]=new Bag<DirectedEdge>();
}
}
public int V(){return V;}
public int E(){return E;}
public void addEdge(DirectedEdge edge){
int v=edge.from();
adj[v].add(edge);
E++;
}
public Iterable<DirectedEdge> adj(int v){
return adj[v];
}
public String toString(){
String s=V+"vertices"+" "+E+"edges\n";
for (int v=0;v<V;v++){
s+=v+":";
for (DirectedEdge edge:this.adj(v)){
int w=edge.to();
s+=w+"("+String.format("%.2f",edge.weight())+"),";
}
s+="\n";
}
return s;
}
public static void main(String[] args){
Random r = new Random();
int V=10;
EdgeWeightDigraph g=new EdgeWeightDigraph(V);
for (int i=0;i<2*V;i++){
int w=r.nextInt(V-1);
int v=r.nextInt(V-1);
double weight=r.nextDouble();
DirectedEdge edge=new DirectedEdge(w,v,weight);
g.addEdge(edge);
}
//for (int w:g.adj(1)) System.out.println(w+"");
System.out.println(g);
}
}