-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiGraph.java
More file actions
62 lines (56 loc) · 1.47 KB
/
DiGraph.java
File metadata and controls
62 lines (56 loc) · 1.47 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
55
56
57
58
59
60
61
62
import java.util.Random;
public class DiGraph{
private int V;
private int E=0;
private Bag<Integer>[] adj;
public DiGraph(int v){
this.V=v;
adj=(Bag<Integer>[]) new Bag[v];
for (int i=0;i<v;i++){
adj[i]=new Bag<Integer>();
}
}
public int V(){return V;}
public int E(){return E;}
public void addEdge(int v,int w){
adj[v].add(w);
E++;
}
public DiGraph reverse(){
DiGraph rev=new DiGraph(this.V);
for (int i=0;i<this.V;i++){
for (int w:this.adj(i)){
rev.addEdge(w, i);
}
}
return rev;
}
public Iterable<Integer> 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 (int w:this.adj(v)){
s+=w+",";
}
s+="\n";
}
return s;
}
public static void main(String[] args){
Random r = new Random();
int V=10;
DiGraph g=new DiGraph(V);
for (int i=0;i<2*V;i++){
int w=r.nextInt(V-1);
int v=r.nextInt(V-1);
if (w==v) continue;
g.addEdge(v,w);
}
//for (int w:g.adj(1)) System.out.println(w+"");
System.out.println(g);
System.out.println(g.reverse());
}
}