-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.java
78 lines (70 loc) · 1.91 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.ArrayList;
import java.util.HashMap;
/**
* Graph represented by adjacency list with hospitals.
*/
class Graph {
private final HashMap<Integer, ArrayList<Integer>> adjacencyList = new HashMap<>();
private final ArrayList<Integer> hospitals = new ArrayList<>();
private final ArrayList<Integer> nodes = new ArrayList<>();
/**
* Adds edge to adjacency list.
*
* @param firstNode Node 1.
* @param secondNode Node 2.
*/
void addEdge(String firstNode, String secondNode) {
int node1 = Integer.parseInt(firstNode);
int node2 = Integer.parseInt(secondNode);
adjacencyList.computeIfAbsent(node1, k -> new ArrayList<>());
adjacencyList.get(node1).add(node2);
}
/**
* Adds hospital to hospitals list.
*
* @param hospital Hospital to add.
*/
void addHospital(int hospital) {
if (adjacencyList.containsKey(hospital)) {
hospitals.add(hospital);
} else {
System.out.println("Hospital " + hospital + " is omitted as it is not in the graph!");
}
}
/**
* Returns hospital list.
*
* @return ArrayList of hospitals.
*/
ArrayList<Integer> getHospitals() {
return hospitals;
}
/**
* Returns adjacency list.
*
* @return HashMap of node and its adjacency list.
*/
HashMap<Integer, ArrayList<Integer>> getAdjacencyList() {
return adjacencyList;
}
/**
* Adds node to nodes list.
*
* @param node Node to add.
*/
void addNodes(int node) {
if (adjacencyList.containsKey(node)) {
nodes.add(node);
} else {
System.out.println("Node " + node + " is omitted as it is not in the graph!");
}
}
/**
* Returns nodes list.
*
* @return ArrayList of nodes.
*/
ArrayList<Integer> getNodes() {
return nodes;
}
}