Course Schedule II; BFS; DFS;
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Course Schedule II; BFS; DFS;相关的知识,希望对你有一定的参考价值。
We can use bfs to solve this problem;
By traverse the prerequisites array, we can generate two graph representations. One is an array of list of out nodes of a certain node. The other is an array of list of in nodes of a certain node.
We look into each course(node), if its out nodes list is empty, that means the node is an isolate node or an sink node(the end node of a connected component of the graph). We add those course node into the from the end part of result array(the order can be random). If it has in nodes find all of them in the list of in nodes list of current node and then remove current node in the out node list of each in node we found above. Then we go to the first step to findout new nodes which has no out nodes.
public class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { int[] courseOrder = new int[numCourses]; List<Integer>[] graph_in = (List<Integer>[]) new List[numCourses]; List<Integer>[] graph_out = (List<Integer>[]) new List[numCourses]; for(int i = 0; i < prerequisites.length; i++){ int inNode = prerequisites[i][1]; int outNode = prerequisites[i][0]; if(graph_in[inNode] == null) graph_in[inNode] = new ArrayList<>(); if(graph_out[outNode] == null) graph_out[outNode] = new ArrayList<>(); graph_in[inNode].add(outNode); graph_out[outNode].add(inNode); } //boolean[] isMark = new boolean[numCourses]; boolean[] added = new boolean[numCourses]; //boolean[] inCircle = new boolean[numCourses]; int j = numCourses-1; while(j >= 0){ int temp = j; for(int i = 0; i < numCourses; i++){ int outNode = i; if(!added[i] && (graph_in[i] == null || graph_in[i].isEmpty())){ courseOrder[j] = i; added[i] = true; j--; List<Integer> list = graph_out[i]; if(list == null) continue; for(int k = 0; k < list.size(); k++){ graph_in[list.get(k)].remove(Integer.valueOf(i)); } } } if(j == temp) return new int[0]; } return courseOrder; } }
以上是关于Course Schedule II; BFS; DFS;的主要内容,如果未能解决你的问题,请参考以下文章