LeetCode Course Schedule

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?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

click to show more hints.

Hints:
  1. This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. There are several ways to represent a graph. For example, the input prerequisites is a graph represented by a list of edges. Is this graph representation appropriate?
  3. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  4. Topological sort could also be done via BFS.
 1 class Node {

 2 public:

 3     int in;

 4     vector<int> req;

 5     Node():in(0){}

 6 };

 7 

 8 class Solution {

 9 public:

10     bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {

11         vector<Node> nodes(numCourses);

12         int len = prerequisites.size();

13         for (int i=0; i<len; i++) {

14             nodes[prerequisites[i][0]].req.push_back(prerequisites[i][1]);

15             nodes[prerequisites[i][1]].in++;

16         }

17         queue<int> zeros;

18         for (int i = 0; i<numCourses; i++) {

19             if (nodes[i].in == 0 && nodes[i].req.size() != 0) {

20                 zeros.push(i);

21             }

22         }

23         while (!zeros.empty()) {

24             int first = zeros.front();

25             zeros.pop();

26             

27             nodes[first].in = -1;

28             for (int k=0; k<nodes[first].req.size(); k++) {

29                 if (--nodes[nodes[first].req[k]].in == 0) {

30                     zeros.push(nodes[first].req[k]);

31                 }

32             }

33         }

34         for (int i=0; i<numCourses; i++) {

35             if (nodes[i].in > 0 && nodes[i].req.size() != 0) return false;

36         }

37         return true;

38     }

39 };

273ms感觉时间复杂度不行,有待改进

你可能感兴趣的:(LeetCode)