Course Schedule (I & II)

有向图,尽量用BFS去做,明确,而且不stack overflow。(有向图,不选Union Find)

Course Schedule II

BFS, BFS的有向图建立indegree vector来做。无向图不行,无向图需要用set,来删除节点。

class Solution {
public:
    vector findOrder(int numCourses, vector>& prerequisites) {
        vector ret;
        vector> graph(numCourses, vector());
        vector in(numCourses, 0);
        for(auto it : prerequisites){
            graph[it.second].push_back(it.first);
            in[it.first]++;
        }
        queue q;
        for(int i=0; i();
    }
};

DFS:

DFS有向图,需要建立visited vector, int, 取0,-1,1. 其中 -1表示有loop。无向图,将前一个节点,作为pre带去dfs函数中,如果相等则continue。

class Solution {
public:
    vector findOrder(int numCourses, vector>& prerequisites) {
        vector ret;
        vector> graph(numCourses, vector());
        for(auto it : prerequisites){
            graph[it.second].push_back(it.first);
        }
        vector visited(numCourses, 0);
        for(int i=0; i();
        }
        if(ret.size() != numCourses) return vector();
        reverse(ret.begin(), ret.end());
        return ret;
    }
    
    bool dfs(vector> &graph, vector &visited, vector &ret, int cur){
        if(visited[cur] == -1) return false;
        else if(visited[cur] == 1) return true;
        visited[cur] = -1;
        for(auto it : graph[cur]){
            if(!dfs(graph, visited, ret, it)) return false;
        }
        visited[cur] = 1;
        ret.push_back(cur);
        return true;
    }
};

你可能感兴趣的:(Course Schedule (I & II))