# easily understand 9ms JAVA solution using BFS with topological sorting

• This solution is based on BFS and topological sorting algorithm.
I was inspired a solution in Course Schedule, here is the problem: link text. But I can't find the solution now. I will add the link later. ^^
We need an adjacent table to record the relationship between prerequisite course and current course.
Also, we need an indegree table to record the number of courses we need to taken in order to take this current course.
queue is to record the course with indegree 0, which means we can take this course immediately without limitation.
Once we take the course with indegree 0, we can look up other courses which require this course as prerequisite and subtract their indegree by 1.
Once the indegree is 0, add this course to the queue.
before return, we need to check if there's a circle.

``````public int[] findOrder(int numCourses, int[][] prerequisites) {
for(int i = 0; i < numCourses; i++){
}
// define an indegree table recording the number of prerequisite courses should be taken in order to take this current course
int[] indegree = new int[numCourses];
int[] result = new int[numCourses];
for(int i = 0; i < prerequisites.length; i++){
int preCourses = prerequisites[i][1];
int curCourses = prerequisites[i][0];
indegree[curCourses]++;
}
// to find the course with indegree 0 (which we can take immediately)
for(int i = 0; i < numCourses; i++){
if(indegree[i] == 0){
}
}
int count = 0;
// if we take the course with indegree 0, we look up for the courses needing this course as prerequisite and subtract their indegree value by 1