2019年11月7日 星期四

Course Schedule


Course Schedule

  • Lintcode : 615 / Leetcode : 207
  • Level : Medium

Problem

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
Example 1:

Input: n = 2, prerequisites = [[1,0]] 
Output: true
Example 2:

Input: n = 2, prerequisites = [[1,0],[0,1]] 
Output: false

Concept & Algorithm

Time Complexity & Space Complexity

time : O(n)
space: O(n)

Answer

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        // [[5,8],[3,5],[1,9],[4,5],[0,2],[1,9],[7,8],[4,9]]
        // used set<int> will cause error
        vector<unordered_multiset<int>> edges(numCourses);
        vector<int> degree(numCourses, 0);
        for (auto p : prerequisites) {
            edges[p.second].insert(p.first);
            degree[p.first]++;
        }
        queue<int> q;
        set<int> course;
        for (int i = 0; i < degree.size(); i++) {
            if (degree[i] == 0) {
                q.push(i);
            }
        }
        while (!q.empty()) {
            int head = q.front(); q.pop();
            course.insert(head);
            for (auto it = edges[head].begin(); it != edges[head].end(); it++) {
                degree[*it]--;
                if (degree[*it] == 0) {
                    q.push(*it);
                }
            }
        }
        return course.size() == numCourses;
    }
};
tags: topological sorting

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...