1
- ### Graph
1
+ ##Graph
2
2
==========
3
3
4
4
NOTES:
@@ -10,7 +10,6 @@ class Node { //using adjacency list
10
10
int data;
11
11
boolean visited;
12
12
List<Node > list = new ArrayList<> ();
13
- void print () {};
14
13
}
15
14
16
15
void bfs(Node root) {
@@ -19,7 +18,6 @@ void bfs(Node root) {
19
18
root. visited = true ;
20
19
while (! queue. isEmpty()) {
21
20
Node current = queue. poll();
22
- current. print();
23
21
for (Node i : current. list) {
24
22
if (! i. visited) {
25
23
current. visited = true ;
@@ -92,7 +90,7 @@ enum Color {
92
90
}
93
91
94
92
void topSort(List<Node > nodes) {
95
- List<Node > sorted = new ArrayList<> ();
93
+ List<Node > sorted = new ArrayList<> (); // will contain the sorted graph
96
94
Map<Node , Color > state = new HashMap<> ();
97
95
Set<Node > path = new LinkedHashSet<> ();
98
96
List<Set<Node > > paths = new ArrayList<> ();
@@ -117,17 +115,24 @@ void dfs(Node node,
117
115
118
116
for (Node n : node. list) {
119
117
Color color = state. get(n);
120
- if (color == GRAY ) throw new IllegalStateException (" Cycle Detection" );
121
- if (color == BLACK ) continue ;
118
+ if (color == GRAY ) {
119
+ throw new IllegalStateException (" Cycle Detection" );
120
+ }
121
+
122
+ if (color == BLACK ) {
123
+ continue ;
124
+ }
125
+
122
126
path. add(n);
123
127
Set<Node > newPath = new LinkedHashSet<> (path);
124
- dfs(n, sorted, state, new LinkedHashSet (newPath));
128
+ dfs(n, sorted, state, new LinkedHashSet (newPath), paths, outOrder );
125
129
}
126
130
127
131
state. put(node, Color . BLACK );
128
132
sorted. add(node);
129
133
paths. add(path);
130
134
135
+ // update outorder
131
136
for (Node n : node. list) {
132
137
outOrder(n, outOrder. get(n) + 1 );
133
138
}
@@ -138,6 +143,7 @@ Map<Node, Integer> getNodesOutOrder(List<Node> nodes) {
138
143
Map<Node , Color > state = new HashMap<> ();
139
144
Set<Node > path = new LinkedHashSet<> ();
140
145
List<Set<Node > > paths = new ArrayList<> ();
146
+ // initialize
141
147
for (Node n : nodes) {
142
148
outOrder. put(n, 0 );
143
149
}
0 commit comments