LeetCode 210. 课程表 II
思路
topsort,需要先完成的指向后完成的,入读为0,则无前继课程或前继课程已被防止在list中
代码
class Solution {
static int V;
static int[] degree;
static int[] head;
static edge[] edges;
static int count;
static class edge {
int to;
int next;
public edge(int to, int next) {
this.to = to;
this.next = next;
}
}
public static int[] findOrder(int numCourses, int[][] prerequisites) {
count=0;
if(prerequisites.length==0) {
int [] re=new int[numCourses];
for(int i=0;i<re.length;i++)re[i]=i;
return re;
}
V = numCourses;
degree = new int[V];
head = new int[V];
edges = new edge[prerequisites.length];
for (int i = 0; i < V; i++)
head[i] = -1;
for (int i = 0; i < edges.length; i++) {
addEdge(prerequisites[i][1], prerequisites[i][0]);
}
return getRes();
}
public static int[] getRes() {
Queue<Integer> queue=new LinkedList<Integer>();
for(int i =0;i<V;i++) {
if(degree[i]==0)queue.offer(i);
}
ArrayList<Integer> list=new ArrayList<Integer>();
while(!queue.isEmpty()) {
int k=queue.poll();
list.add(k);
int tmphead=head[k];
while(tmphead!=-1) {
if(--degree[edges[tmphead].to]==0) {
queue.offer(edges[tmphead].to);
}
tmphead=edges[tmphead].next;
}
}
if(list.size()<V)return new int[0];
int [] re=new int[list.size()];
for(int i =0;i<re.length;i++)re[i]=list.get(i);
return re;
}
public static void addEdge(int from, int to) {
edges[count] = new edge(to, head[from]);
head[from] = count++;
degree[to]++;
}
}