java 210.课程表II(#1拓扑排序).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 210.课程表II(#1拓扑排序).java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        List<List<Integer>> adjList = new ArrayList<List<Integer>>();
        
        for(int i = 0; i < numCourses; i++){
            adjList.add(new ArrayList<Integer>());
        }
        
        for(int i = 0; i < prerequisites.length; i++){
            int start = prerequisites[i][0];
            int end = prerequisites[i][1];
            adjList.get(start).add(end);
        }
        
        int[] explored = new int[numCourses];
        LinkedList<Integer> resTemp = new LinkedList<Integer>();
        //int[] res = null;
        for(int i = 0; i < numCourses; i++){
            if(explored[i] == 2){
                continue;
            }
            if(hasCycle(adjList, i, explored, resTemp)){
                return new int[0];
            }
        }
        
        int[] res = new int[numCourses];
        
        for(int i = 0; i < resTemp.size(); i++){
            res[i] = resTemp.get(i);
        }
        return res;
    }
    
    public boolean hasCycle(List<List<Integer>> adjList, int cur, int[] explored, LinkedList<Integer> res){
        
        explored[cur] = 1;
        for(int i = 0; i < adjList.get(cur).size(); i++){
            int temp = adjList.get(cur).get(i);
            if(explored[temp] == 1) {
                return true;
            } else if(explored[temp] == 0) {
                if(hasCycle(adjList, temp, explored, res)){
                    return true;
                }
            }
        }
        explored[cur] = 2;
        res.add(new Integer(cur));
        return false;
    }
}
class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        List<List<Integer>> adjList = new ArrayList<>();
        int[] indegree = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            adjList.add(new ArrayList<>());
        }
        for (int[] e : prerequisites) {
            adjList.get(e[1]).add(e[0]);
            indegree[e[0]]++;
        }
        Queue<Integer> q = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (indegree[i] == 0) {
                q.offer(i);
            }
        }
        int[] res = new int[numCourses];
        int k = 0;
        while (!q.isEmpty()) {
            int cur = q.poll();
            res[k++] = cur;
            for (int i : adjList.get(cur)) {
                if (--indegree[i] == 0) {
                    q.offer(i);
                }
            }
        }
        return k == numCourses ? res : new int[0];
    }
}

以上是关于java 210.课程表II(#1拓扑排序).java的主要内容,如果未能解决你的问题,请参考以下文章

java 210.课程表II(#1拓扑排序).java

java 210.课程表II(#1拓扑排序).java

java 210.课程表II(#1拓扑排序).java

java 210.课程表II(#1拓扑排序).java

leetcode 210. 课程表 II----拓扑排序篇二

拓扑排序,YYDS!