-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
TopologicalSorting.java
46 lines (36 loc) · 1.14 KB
/
TopologicalSorting.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
package algo.graph;
import ds.graph.Graph;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by sherxon on 1/4/17.
*/
public class TopologicalSorting extends DFS {
List<Integer> list;
public TopologicalSorting(Graph graph) {
super(graph);
list = new ArrayList<>();
}
// this works with DAG Only
// first we will choose any vertex who that does not have incoming edges (sources)
// sources can be found easier if incoming edge count is recorded in each vertex
List<Integer> topSort() {
Set<Integer> sources = new HashSet<>();
for (Integer vertex : graph.getVertices())
sources.add(vertex);
for (Integer vertex : graph.getVertices())
for (Integer tVertex : graph.getNeighbors(vertex))
sources.remove(tVertex);
for (Integer source : sources)
if (!visited.contains(source))
search(source);
return list;
}
@Override
public void processVertex(Integer source) {
super.processVertex(source);
list.add(source);
}
}