1. 程式人生 > >Leetcode 207. 課程表

Leetcode 207. 課程表

site delet rap 表示 pan () 一個 返回 lse

class Solution {
public:
    struct GraphNode
    {
        int lable;
        vector<GraphNode*> neighbors;
        GraphNode(int x):lable(x){}
    };
    
    bool DFS_graph(GraphNode* node, vector<int>& visit)
    {
        //正在訪問
        visit[node->lable] = 0;
        for(int i=0
; i<node->neighbors.size(); ++i) { if(visit[node->neighbors[i]->lable] == -1) { //在訪問的裏面已經返回false就直接返回false了 if(DFS_graph(node->neighbors[i], visit) == 0) { return false; } }
// 第一個遇到有環的 if(visit[node->neighbors[i]->lable] == 0) { return false; } } //完成了以後 visit[node->lable] = 1; return true; } bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { vector
<GraphNode*> graph; vector<int> visit;//節點狀態,-1表示沒有訪問,0表示正在訪問,1表示已經訪問 bool flag = true; for(int i=0; i<numCourses; ++i) { graph.push_back(new GraphNode(i)); } visit.resize(numCourses, -1); for(int i=0; i<prerequisites.size(); ++i) { GraphNode* begin = graph[prerequisites[i].second]; GraphNode* end = graph[prerequisites[i].first]; begin->neighbors.push_back(end); } for(int i=0; i<graph.size(); ++i) { if(visit[i] == -1 && !DFS_graph(graph[i], visit)) { flag = false; break; } } for(int i=0; i<numCourses; ++i) { delete graph[i]; } return flag; } };

 bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<GraphNode*> graph;
        vector<int> degree;
            
        for(int i=0; i<numCourses; ++i)
        {
            graph.push_back(new GraphNode(i));
        }
        degree.resize(numCourses, 0);
        
        for(int i=0; i<prerequisites.size(); ++i)
        {
            GraphNode* begin = graph[prerequisites[i].second];
            GraphNode* end = graph[prerequisites[i].first];
            begin->neighbors.push_back(end);
            ++degree[prerequisites[i].first];
        }
        queue<GraphNode*> queue;
        for(int i=0; i<numCourses; ++i)
        {
            if(degree[i] == 0)
            {
                queue.push(graph[i]);
            }
        }
            
        while(!queue.empty())
        {
            auto *node = queue.front();
            queue.pop();
            for(int i=0; i<node->neighbors.size(); ++i)
            {
                --degree[node->neighbors[i]->lable];
                if(degree[node->neighbors[i]->lable] == 0)   
                {
                    queue.push(node->neighbors[i]);
                }  
            }
        }
        for(int i=0; i<numCourses; ++i )
            delete graph[i];
        
        for(int i=0; i<degree.size(); ++i)
        {
            if(degree[i])
                return false;
        }
        return true;
    }
};

Leetcode 207. 課程表