-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathBeanGraph.java
More file actions
90 lines (77 loc) · 2.58 KB
/
BeanGraph.java
File metadata and controls
90 lines (77 loc) · 2.58 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package arhangel.dim.container;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*/
public class BeanGraph {
// Граф представлен в виде списка связности для каждой вершины
private Map<BeanVertex, List<BeanVertex>> vertices = new HashMap<>();
/**
* Добавить вершину в граф
* @param value - объект, привязанный к вершине
*/
public BeanVertex addVertex(Bean value) {
BeanVertex newVert = new BeanVertex(value);
vertices.put(newVert, new ArrayList<BeanVertex>());
return newVert;
}
/**
* Соединить вершины ребром
* @param from из какой вершины
* @param to в какую вершину
*/
public void addEdge(BeanVertex from ,BeanVertex to) {
getLinked(from).add(to);
}
/**
* Проверяем, связаны ли вершины
*/
public boolean isConnected(BeanVertex v1, BeanVertex v2) {
return getLinked(v1).contains(v2);
}
/**
* Получить список вершин, с которыми связана vertex
*/
public List<BeanVertex> getLinked(BeanVertex vertex) {
return vertices.get(vertex);
}
/**
* Количество вершин в графе
*/
public int size() {
return vertices.size();
}
private enum Color {
GRAY,
BLACK
}
private void sortDfs(BeanVertex vertex,
Map<BeanVertex, Color> vertexColor,
List<BeanVertex> output) throws CycleReferenceException {
vertexColor.put(vertex, Color.GRAY);
for (BeanVertex neighbour: getLinked(vertex)) {
if (vertexColor.containsKey(neighbour)) {
if (vertexColor.get(neighbour) == Color.GRAY) {
throw new CycleReferenceException("There is cyclical references here. Sorry.");
}
} else {
sortDfs(neighbour, vertexColor, output);
}
}
vertexColor.put(vertex, Color.BLACK);
output.add(vertex);
}
public List<BeanVertex> sort() throws CycleReferenceException {
Map<BeanVertex, Color> vertexState = new HashMap<>();
List<BeanVertex> order = new ArrayList<>();
for (BeanVertex v: vertices.keySet()) {
if (!vertexState.containsKey(v)) {
sortDfs(v, vertexState, order);
}
}
return order;
}
}