比起207题有向图环的检测,多了一个要求是将后序遍历的结果反转,即得到拓扑排序的结果
// 记录后序遍历结果
List<Integer> postorder = new ArrayList<>();
DFS步骤:
- 图的建立
List<Integer>[] buildGraph(int numCourses, int[][] prerequisites)
- DFS遍历
void traverse(List<Integer>[] graph, int s)
- 反转结果
Collections.reverse(postorder);
class Solution {
boolean[] visited;
boolean[] onPath;
boolean hasCycle;
// 记录后序遍历结果
List<Integer> postorder = new ArrayList<>();
public int[] findOrder(int numCourses, int[][] prerequisites) {
visited = new boolean[numCourses];
onPath = new boolean[numCourses];
List<Integer>[] graph = buildGraph(numCourses,prerequisites);
for(int i = 0;i<numCourses;i++){
travel(graph,i);
}
if(hasCycle){
return new int[]{};
}
Collections.reverse(postorder);
int[] res = new int[numCourses];
for(int i = 0;i<numCourses;i++){
res[i] = postorder.get(i);
}
return res;
}
List<Integer>[] buildGraph(int numCourses,int[][] prerequisites){
List<Integer>[] graph = new LinkedList[numCourses];
for(int i = 0;i<numCourses;i++){
graph[i] = new LinkedList<Integer>();
}
for(int edge[] : prerequisites){
int from = edge[1];
int to = edge[0];
graph[from].add(to);
}
return graph;
}
void travel(List<Integer>[] graph,int start){
if(onPath[start]){
hasCycle = true;
}
if(hasCycle||visited[start]){
return;
}
visited[start] = true;
onPath[start] = true;
for(int w:graph[start]){
travel(graph,w);
}
postorder.add(start);
onPath[start] = false;
}
}
BFS:
- 图的建立
List<Integer>[] buildGraph(int numCourses, int[][] prerequisites)
- 建立入度数组、BFS
将入度为0的from节点入队,在出队时,出队的from节点加入结果res中,并将from节点对应的to节点的入度-1,判断入度是否为0,将入度为0的节点加入队列
如果最终所有节点都被遍历过(count 等于节点数),则说明不存在环,反之则说明存在环。