forked from lahiruroot/Java-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.java
48 lines (40 loc) · 1.29 KB
/
Graph.java
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
package Graph;
import java.util.ArrayList;
import java.util.HashMap;
public class Graph {
private HashMap<String, ArrayList<String>> adjList = new HashMap<>();
public boolean addVertex(String vertex){
if (adjList.get(vertex)==null){
adjList.put(vertex, new ArrayList<String>());
return true;
}
return false;
}
public boolean addEdge(String vertex1, String vertex2){
if (adjList.get(vertex1) !=null && adjList.get(vertex2) != null){
adjList.get(vertex1).add(vertex2);
adjList.get(vertex2).add(vertex1);
return true;
}
return false;
}
public boolean removeEdge(String vertex1, String vertex2){
if (adjList.get(vertex1) !=null && adjList.get(vertex2) != null){
adjList.get(vertex1).remove(vertex2);
adjList.get(vertex2).remove(vertex1);
return true;
}
return false;
}
public boolean removeVertex(String vertex){
if (adjList.get(vertex) == null) return false;
for (String otherVertex:adjList.get(vertex)) {
adjList.get(otherVertex).remove(vertex);
}
adjList.remove(vertex);
return true;
}
public void printGraph(){
System.out.println(adjList);
}
}