-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectedGraph.java
More file actions
41 lines (40 loc) · 1.15 KB
/
DirectedGraph.java
File metadata and controls
41 lines (40 loc) · 1.15 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
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class DirectedGraph<T> {
private HashMap<T,ArrayList<T>> nodes;
DirectedGraph(){
nodes=new HashMap<T,ArrayList<T>>();
}
public void addVertex(T V){
nodes.put(V,new ArrayList<T>());
}
public void addEdge(T u,T v){
nodes.get(u).add(v);
}
public ArrayList<T> getAdjacentNodes(T vertex){
return nodes.get(vertex);
}
public void printGraph(){
Set<T> vertices=nodes.keySet();
Iterator<T> i=vertices.iterator();
while(i.hasNext()){
T a=i.next();
System.out.print(a+": ");
for(int j=0;j<nodes.get(a).size();j++){
System.out.print(nodes.get(a).get(j)+" ");
}
System.out.println();
}
}
public ArrayList<T> getVertices(){
Set<T> s=nodes.keySet();
Iterator<T> i=s.iterator();
ArrayList<T> vertices=new ArrayList<T>();
while(i.hasNext()){
vertices.add(i.next());
}
return vertices;
}
}