-
Notifications
You must be signed in to change notification settings - Fork 104
/
Solution.java
279 lines (219 loc) · 7.18 KB
/
Solution.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/// Leetcode 210. Course Schedule II
/// https://leetcode.com/problems/course-schedule-ii/
///
/// 课程中在这里暂时没有介绍这个问题
/// 该代码主要用于使用 Leetcode 上的问题测试我们的 TopSort2 算法类
import java.io.File;
import java.io.IOException;
import java.util.*;
class Solution {
public class Graph implements Cloneable{
private int V;
private int E;
private TreeSet<Integer>[] adj;
private boolean directed;
private int[] indegrees, outdegrees;
public Graph(int V, boolean directed){
this.directed = directed;
this.V = V;
this.E = 0;
adj = new TreeSet[V];
for(int i = 0; i < V; i ++)
adj[i] = new TreeSet<Integer>();
indegrees = new int[V];
outdegrees = new int[V];
}
public void addEdge(int a, int b){
validateVertex(a);
validateVertex(b);
adj[a].add(b);
outdegrees[a] ++;
indegrees[b] ++;
if(!directed)
adj[b].add(a);
}
public boolean isDirected(){
return directed;
}
public void validateVertex(int v){
if(v < 0 || v >= V)
throw new IllegalArgumentException("vertex " + v + "is invalid");
}
public int V(){
return V;
}
public int E(){
return E;
}
public boolean hasEdge(int v, int w){
validateVertex(v);
validateVertex(w);
return adj[v].contains(w);
}
public Iterable<Integer> adj(int v){
validateVertex(v);
return adj[v];
}
public int degree(int v){
if(!directed) throw new RuntimeException("degree only works in undirected graph.");
validateVertex(v);
return adj[v].size();
}
public int indegree(int v){
if(!directed) throw new RuntimeException("indegree only works in directed graph.");
validateVertex(v);
return indegrees[v];
}
public int outdegree(int v){
if(!directed) throw new RuntimeException("outdegree only works in directed graph.");
validateVertex(v);
return outdegrees[v];
}
public void removeEdge(int v, int w){
validateVertex(v);
validateVertex(w);
if(adj[v].contains(w)){
E --;
if(directed){
indegrees[w] --;
outdegrees[v] --;
}
}
adj[v].remove(w);
if(!directed)
adj[w].remove(v);
}
@Override
public Object clone(){
try{
Graph cloned = (Graph) super.clone();
cloned.adj = new TreeSet[V];
for(int v = 0; v < V; v ++){
cloned.adj[v] = new TreeSet<Integer>();
for(int w: adj[v])
cloned.adj[v].add(w);
}
return cloned;
}
catch (CloneNotSupportedException e){
e.printStackTrace();
}
return null;
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append(String.format("V = %d, E = %d, directed = %b\n", V, E, directed));
for(int v = 0; v < V; v ++){
sb.append(String.format("%d : ", v));
for(int w : adj[v])
sb.append(String.format("%d ", w));
sb.append('\n');
}
return sb.toString();
}
}
public class DirectedCycleDetection {
private Graph G;
private boolean[] visited;
private boolean[] onPath;
private boolean hasCycle = false;
public DirectedCycleDetection(Graph G){
if(!G.isDirected())
throw new IllegalArgumentException("DirectedCycleDetection only works in directed graph.");
this.G = G;
visited = new boolean[G.V()];
onPath = new boolean[G.V()];
for(int v = 0; v < G.V(); v ++)
if(!visited[v])
if(dfs(v)){
hasCycle = true;
break;
}
}
// 从顶点 v 开始,判断图中是否有环
private boolean dfs(int v){
visited[v] = true;
onPath[v] = true;
for(int w: G.adj(v))
if(!visited[w]){
if(dfs(w)) return true;
}
else if(onPath[w])
return true;
onPath[v] = false;
return false;
}
public boolean hasCycle(){
return hasCycle;
}
}
public class GraphDFS {
private Graph G;
private boolean[] visited;
private ArrayList<Integer> pre = new ArrayList<>();
private ArrayList<Integer> post = new ArrayList<>();
public GraphDFS(Graph G){
this.G = G;
visited = new boolean[G.V()];
for(int v = 0; v < G.V(); v ++)
if(!visited[v])
dfs(v);
}
private void dfs(int v){
visited[v] = true;
pre.add(v);
for(int w: G.adj(v))
if(!visited[w])
dfs(w);
post.add(v);
}
public Iterable<Integer> pre(){
return pre;
}
public Iterable<Integer> post(){
return post;
}
}
public class TopoSort2 {
private Graph G;
private ArrayList<Integer> res;
private boolean hasCycle = false;
public TopoSort2(Graph G){
if(!G.isDirected())
throw new IllegalArgumentException("DirectedCycleDetection only works in directed graph.");
this.G = G;
res = new ArrayList<>();
hasCycle = (new DirectedCycleDetection(G)).hasCycle();
if(hasCycle) return;
GraphDFS dfs = new GraphDFS(G);
for(int v: dfs.post())
res.add(v);
Collections.reverse(res);
}
public boolean hasCycle(){
return hasCycle;
}
public ArrayList<Integer> result(){
return res;
}
}
public int[] findOrder(int numCourses, int[][] prerequisites) {
Graph g = new Graph(numCourses, true);
for(int[] e: prerequisites)
g.addEdge(e[1], e[0]);
TopoSort2 topoSort = new TopoSort2(g);
if(topoSort.hasCycle()) return new int[0];
int[] res = new int[numCourses];
for(int i = 0; i < numCourses; i ++)
res[i] = topoSort.result().get(i);
return res;
}
public static void main(String[] args){
int[][] pre = {{0, 1}, {1, 0}};
int[] res = (new Solution()).findOrder(2, pre);
System.out.println("res size : " + res.length);
for(int e: res) System.out.print(e + " ");
System.out.println();
}
}