java 207.课程表(#Topological Sort).java

Posted

tags:

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

public class Solution {
    public boolean canFinish(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];
        
        for(int i = 0; i < numCourses; i++){
            if(explored[i] == 2){//优化!!!
                continue;
            }
            if(hasCycle(adjList, explored, i)){
                return false;
            }
        }
        
        return true;
        
    }
    
    public boolean hasCycle(List<List<Integer>> adjList, int[] explored, int cur){
        
        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, explored, temp)) {
                    return true;
                }
            }
        }
        explored[cur] = 2;
        return false;
        
    }
}


/*
2
[[1,0]]
2
[[1,0],[0,1]]
5
[[0,1],[1,2],[1,3],[1,4],[2,3]]

*/
class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        if (prerequisites == null || prerequisites.length < 1 || prerequisites[0].length < 1) return true;
        List<List<Integer>> adj = new ArrayList<>();
        int[] indegree = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            adj.add(new ArrayList<>());
        }
        for (int[] e : prerequisites) {
            adj.get(e[0]).add(e[1]);
            indegree[e[1]]++;
        }
        Queue<Integer> q = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (indegree[i] == 0) {
                q.add(i);
            }
        }
        int cnt = 0;
        while (!q.isEmpty()) {
            int cur = q.poll();
            cnt++;
            for (int next : adj.get(cur)) {
                if (--indegree[next] == 0) {
                    q.offer(next);
                }
            }
        }
        return cnt == numCourses;
    }
}

以上是关于java 207.课程表(#Topological Sort).java的主要内容,如果未能解决你的问题,请参考以下文章

java 207.课程表(#Topological Sort).java

java 207.课程表(#Topological Sort).java

java 207.课程表(#Topological Sort).java

java 207.课程表(#Topological Sort).java

Topological Sor-207. Course Schedule

[leetcode]Topological Sort-207. Course Schedule