forked from xtaci/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdjacentListGraph.java
More file actions
44 lines (36 loc) · 922 Bytes
/
Copy pathAdjacentListGraph.java
File metadata and controls
44 lines (36 loc) · 922 Bytes
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
import java.util.*;
public class AdjacentListGraph {
public class Edge {
int from;
int to;
int weight;
public Edge(int from, int to, int weight){
this.from = from;
this.to = to;
this.weight = weight;
}
}
Map<Integer, List<Edge>> adjacentList;
int V;
public AdjacentListGraph (int V) {
this.V = V;
adjacentList = new HashMap<>();
for (int i = 0; i < V; i ++) {
adjacentList.put(i, new LinkedList<Edge>());
}
}
public void addEdge(int from, int to, int weight) {
List<Edge> adjacentEdge = adjacentList.get(from);
if (adjacentEdge != null) {
adjacentEdge.add(new Edge(from, to, weight));
}
}
public void printGraph(){
for (int vertex = 0; vertex < V; vertex ++ ) {
List<Edge> adjacentEdge = adjacentList.get(vertex);
for (Edge edge: adjacentEdge) {
System.out.println("Edge from " + edge.from + " to " + edge.to + " weight = " + edge.weight);
}
}
}
}