1. 程式人生 > >leetcode 207 課程表 有向圖 鄰接表 判斷是否有環

leetcode 207 課程表 有向圖 鄰接表 判斷是否有環

class Solution {
    struct GraphNode{
        int label;
        vector<GraphNode*>neighbors;
        GraphNode(int x):label(x) {};
    };
    bool DFS_Graph(GraphNode* node,vector<int>&visit){
        visit[node->label]=0;
        for(int i=0;i<node->neighbors.size();i++){
            if(visit[node->neighbors[i]->label]==-1){
                if(!DFS_Graph(node->neighbors[i],visit)){
                    return false;
                }
            }
            else if(visit[node->neighbors[i]->label]==0){
                return false;
            }
        }
        visit[node->label]=1;
        return true;
    }
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<GraphNode*>graph;//臨接表
        vector<int>visit;
        for(int i=0;i<numCourses;i++){
            graph.push_back(new GraphNode(i));
            visit.push_back(-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[1]==-1&&!DFS_Graph(graph[i],visit)){
                return false;
            }
        }
        for(int i=0;i<numCourses;i++){
            delete graph[i];
        }
        return true;
    }
};