【LeetCode】207. Course Schedule

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/KID_LWC/article/details/82494918

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 1:

Input: 2, [[1,0]] 
Output: true
Explanation: There are a total of 2 courses to take. 
             To take course 1 you should have finished course 0. So it is possible.

Example 2:

Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take. 
             To take course 1 you should have finished course 0, and to take course 0 you should
             also have finished course 1. So it is impossible.

题解:本质就是判断是否存在环,注意是有向图,标记数组必须标记三个变量0是未访问,1是在递归栈,2表示已从递归栈出来,所以如果访问到点标记为1说明遇到环,这里必须用邻接表表示图邻接矩阵会超时

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        const int MAXN = 1010;
        vector<int> G[numCourses];
        
        for(int i=0;i<prerequisites.size();i++){
            int u = prerequisites[i].first;
            int v = prerequisites[i].second;
            G[u].push_back(v);
        }
        vector<int> color(numCourses,0);
        for(int i=0;i<numCourses;i++){
            if(!dfs(i,G,color)) return false;
        }
        return true;
    }
    bool dfs(int u,vector<int> G[],vector<int>& color){
        if(color[u]!=0)return color[u]==2;
        color[u]=1;
        
            for(int x:G[u]){
                
                if(color[x]==1||!dfs(x,G,color)) return false;
                if(color[x]==2) continue;
            }
        
        color[u]=2;
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/KID_LWC/article/details/82494918