210 课程表Ⅱ

210 课程表Ⅱ_第1张图片
210 课程表Ⅱ_第2张图片
深度优先搜索

class Solution {
     
private:
    vector<vector<int>> edges;
    vector<int> visited;
    vector<int> result;
    bool invalid;

public:
    void dfs(int u) {
     
        visited[u] = 1;
        for (int v: edges[u]) {
     
            if (visited[v] == 0) {
     
                dfs(v);
                if (invalid) {
     
                    return;
                }
            }
            else if (visited[v] == 1) {
     
                invalid = true;
                return;
            }
        }
        visited[u] = 2;
        result.push_back(u);
    }

    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
     
        edges.resize(numCourses);
        visited.resize(numCourses);
        for (const auto& info: prerequisites) {
     
            edges[info[1]].push_back(info[0]);
        }
        for (int i = 0; i < numCourses && !invalid; ++i) {
     
            if (!visited[i]) {
     
                dfs(i);
            }
        }
        if (invalid) {
     
            return {
     };
        }
        reverse(result.begin(), result.end());
        return result;
    }
};

210 课程表Ⅱ_第3张图片

你可能感兴趣的:(210 课程表Ⅱ)